Page 1 of 1

sending an html message with a plain text attachment

Posted: Wed Dec 19, 2007 1:25 am
by s.dot
I'm trying to send an HTML message with a plain text attachment for those email clients that are not HTML capable. My code looks like this:

Code: Select all

<?php

require_once 'lib/Swift.php';
require_once 'lib/Swift/Connection/SMTP.php';

$log = Swift_LogContainer::getLog();
$log->setLogLevel(4);

$smtp = new Swift_Connection_SMTP('smtp.1and1.com', 25);
$smtp->setUsername('noreply@example.com');
$smtp->setpassword('password');

$swift		= new Swift($smtp);
$message	= new Swift_Message('A simple subject', '<b>A</b> <strong><small>Simple</small> Body</strong>', 'text/html');
$attachment = new Swift_Message_Attachment('A Simple Body', 'email.txt', 'text/plain');
$message->attach($attachment);

if ($swift->send($message, 'me@anotherdomain.com', 'noreply@example.com'))
{
	echo 'sent email';
} else
{
	echo 'did not send email';
	$log = Swift_LogContainer::getLog();
	echo $log->dump(true);
}
The email sends successfully, however the original email is not in HTML format. I do get the plain text message, though.

I thought I might need to make it multi-part, but it's not a multi-part message (at least I don't think). It's just a message with an attachment.

Posted: Wed Dec 19, 2007 3:53 pm
by John Cartwright
Indeed you do want to send a multi-part message and let the email client sort out which part it wants read.

Posted: Thu Dec 20, 2007 12:34 am
by s.dot
Even if I'm sending as an attachment?

Or is the preferred method to send it both HTML and text versions of the email, and let the client do it's thing, like you mentioned? Or, are these the same things?

Posted: Thu Dec 20, 2007 5:44 pm
by Chris Corbyn
scottayy wrote:Even if I'm sending as an attachment?

Or is the preferred method to send it both HTML and text versions of the email, and let the client do it's thing, like you mentioned? Or, are these the same things?
You can't send an attachment like that ;) You need to "attach" your HTML part if you want that to appear as the body because by the very nature of attachements, the email will have more than one document inside it (i.e. the body and the attachment).

Why are you trying to do this using attachments rather than using multipart messages? Either way, this will work:

Code: Select all

$swift      = new Swift($smtp);
$message = new Swift_Message('A simple subject');

$body = new Swift_Message_Part('<b>A</b> <strong><small>Simple</small> Body</strong>', 'text/html');
$message->attach($body);

$attachment = new Swift_Message_Attachment('A Simple Body', 'email.txt', 'text/plain');
$message->attach($attachment);
The documentation regarding sending attachments does mention the fact you need to set your body differently ;)