Swiftmailer is a very good library for sending email from PHP. It has nice object oritented interfaces. However, in recent days I’ve spent a lot of time finding the reason why the content get messed up in Swiftmailer when
- The email has both html and alternate text content
- Embed image in html content
Specification wise, mime structure for HTML with embedded images and plain text fallback is :
multipart/alternative text/plain multipart/related text/html image/png image/png image/jpeg
Swiftmailer has a bug and fails to generate correct mime type entries. The issue is reported here . Thankfully there is a workaround for that.
My previous code was:
$message = Swift_Message::newInstance(); $message->setSubject('Your subject') ->setFrom(array('[email protected]' => 'Saroj Roy')) ->setTo(array('saroj@saroj-HP-ProBook-4530s')) ->setBody('This is a plain text Message','text/plain') ->addPart('Here is the <b>HTML message</b> with image : <img src="' . $message->embed(Swift_Image::fromPath('image.png')). '" alt="Image Missing" />', 'text/html'); $mailer = Swift_Mailer::newInstance(Swift_MailTransport::newInstance()); $result = $mailer->send($message);
I had to change the setBody() to addPart(). This change generates correct mime-type entries in message. However, this is still not 100% full-proof. Problem still occurs in MS Office 2003 and Thunderbird email client when content is viewed as text. These clients convert the html content to text by striping the html-tags out instead of showing the plain-text content. I suppose there are some bugs in these email clients. Please let me know it I were wrong with my assumptions.
By the way, Gmail and console based email client Mutt shows the content correctly.