I'm using PHPmailer and i want to reply to an email. I fetch emails with phpimap along with their message_id
. I'm using PHPmailer to try and reply to an email. I have used the message_id
along with In-Reply-To
in addCustomHeader
. I run the code and when i check the email, it is showing up as a new message and not a reply. Where did i go wrong?
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.domain.co.uk'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'testing'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->addCustomHeader('In-Reply-To', $message_id);
$mail->Sender = '[email protected]';
$mail->Subject = 'testing';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
It's quite reasonable to have every message in a thread using a different subject line, so threading is only dependent on the subject line as a last-resort fallback if you're doing everything else wrong. It's actually quite annoying when clients do this as you end up with unrelated messages that happen to have the same subject grouped together.
Threading and replies are implemented using the References
and In-Reply-To
headers as defined in RFC2822. Read this guide for a thorough description of how to do threading reliably.
The short version is this, for the first reply to a message:
$mail->addCustomHeader('In-Reply-To', $message_id);
$mail->addCustomHeader('References', $message_id);
It gets more complex if the original message is just the latest in a long thread, but it uses the same headers - read the spec and the guide for more info.
Make sure your message ID is correctly formatted - it should be surrounded by <>
, like <[email protected]>
.
You don't need to do anything to the subject line - though it's common to prepend Re:
, it's not necessary for the linkage to work, and it also varies across languages, so it's not something you can rely on.