I have a multi-part email script, that takes a POSTed email address and sends a simple email to them in HTML and/or Plain Text. It displays correctly in Gmail and Outlook, but not eM (and doesn't even get through to a Communigate server). The code:
<?php
$email_address = addslashes($_POST['email_address']);
if (!filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
header("Location: ./?error=invalid-email");
exit();
}
$subject_line = "This is a test multi-part email";
$boundary = uniqid();
$headers = "MIME-Version:1.0
";
$headers .= "From: Maggie Multipart <web@ukipme.com>
";
$headers .= "To: " . $email_address . "
";
$headers .= "Content-Type: multipart/alternative;boundary=" . $boundary . "
";
$message = "This is a MIME encoded message.";
$message .= "
--" . $boundary . "
";
$message .= "Content-Type: text/plain;charset=utf-8
";
$message .= "Hello,
This is a test email, the text/plain version.
Regards
Maggie Multipart";
$message .= "
--" . $boundary . "
";
$message .= "Content-Type: text/html;charset=utf-8
";
$message .= "<p>Hello,<br>This is a test email, the text/html version.</p><p>Regards<br><strong>Maggie Multipart</strong></p>";
$message .= "
--" . $boundary . "--";
mail("", $subject_line, $message, $headers);
header("Location: ./?success=email-sent");
exit();
// var_dump($_POST);
?>
The message is received in eM as follows:
Content-Type: text/plain;charset=utf-8
Hello,
This is a test email, the text/plain version.
Regards
Maggie Multipart
However, eM is set up to receive HTML emails (and does so frequently). Can someone please help me fix this problem? Am I missing any headers?
My general advice for creating emails: Don't do it yourself (with some string concat functions/operators anyway). My weapon of choice is swiftmailer but there are other feasible libraries on the web, too.
<?php
require_once('autoload.php'); // swiftmailer was installed via Composer
$message = Swift_Message::newInstance('This is a test multi-part email')
->setBody(
"Hello,
This is a test email, the text/plain version.
Regards
Maggie Multipart",
'text/plain',
'utf-8'
)
->addPart(
"<p>Hello,<br>This is a test email, the text/html version.</p><p>Regards<br><strong>Maggie Multipart</strong></p>",
'text/html',
'utf-8'
)
->setFrom(array('...@...' => '...'))
->setTo(array('...@...' => '...'));
$transport = Swift_SmtpTransport::newInstance('MSERV', 25, 'tls')
->setUsername('...')
->setPassword('...');
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);