As I expressed in the section that you just read, there's another method included with Swift Mailer that allows you to insert files into an email message. It's called "embed()." This one is extremely intuitive. A concrete example that shows how to use it has been coded below.
Take a look at the pertinent code sample:
// example on sending a basic email message with Swift Mailer (uses the embed() method)
// include required files
// create the mail transport using the 'newInstance()' method
$transport = Swift_SmtpTransport::newInstance('mail.domain.com', 25)
// create the mailer using the 'newInstance()' method
$mailer = Swift_Mailer::newInstance($transport);
// create a simple message using the 'newInstance()' method
$message = Swift_Message::newInstance()
// specify the subject of the message
->setSubject('Testing Swift Mailer')
// specify the From argument
->setFrom(array('firstname.lastname@example.org' => 'Alejandro Gervasio'))
// specify the To argument
->setTo(array('email@example.com' =>' John Doe'))
->setCc(array('firstname.lastname@example.org' => 'Mary Jackson'))
->setBcc(array('email@example.com' => 'Susan Norton'))
// build the body part of the message
->setBody('<html><head></head><body><img src="'. $message->embed(Swift_Image::fromPath('/path/to/file/image1.jpg')). '"</body>');
// send the email message
echo 'The message was sent successfully!';
echo 'Error sending email message';
As depicted above, a sample image file has been inserted directly into a message formatted in HTML via the "embed()" method. For example purposes, I decided to use an instance of the brand new "Swift_Image" class to embed a JPG image within the message's markup, but naturally it's also possible to utilize other file types and obtain the same result.
And with this last example I'm finishing up this ninth tutorial exploring the Swift Mailer library. As always, feel free to tweak the code of all the examples developed in this article, so you can get a more solid background in working with inline attachments.
That's all for now. In this ninth installment of the series I taught you how to use a couple of methods provided by Swift Mailer, which allow you to directly embed attachments into email messages. These can be very helpful, particularly when sending newsletters that contain numerous images which you don't want to be filtered and discarded by popular web-based email systems such as Hotmail and Yahoo.
In the final tutorial I'm going to explore another method of the library called "batchSend()," which allows you to send email messages in a subtly different way.
Here's my final piece of advice: don't miss the last article!
blog comments powered by Disqus