Until now, all of the scripts that worked with attachments used by default the "Content-disposition: attachment" MIME header to annex a file to the message being sent. However, as you may know, the SMTP protocol permits you to handle inline attachments very easily, which has been taken into account by the Swift Mailer development team as well.
The library provides basically two ways of embedding files into messages. Both use methods that belong to different classes. The first option comes with the "setDisposition()" method, which is available within the "Swift_Attachment" class, while the second choice is the "embed()" method, which is included with the "Swift_Message" class.
Does this sound a bit confusing to you? Well, to clear things up, let me start by showing you a script that uses the "setDisposition()" method to embed an image file into an email message. Take a look at it:
// example on sending a basic email message with Swift Mailer (uses the 'addPart()' method, the Swift_Attachment class and the setDisposition() 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('email@example.com' => 'Alejandro Gervasio'))
// specify the To argument
->setTo(array('firstname.lastname@example.org' =>' John Doe'))
->setCc(array('email@example.com' => 'Mary Jackson'))
->setBcc(array('firstname.lastname@example.org' => 'Susan Norton'))
// build the body part of the message
->setBody('Hey, how are you? I am sending you a message with the cool Swift Mailer library. Make sure to check the attached file!')
->addPart('<p>This part of the message has been formatted as HTML to make it look nicer</p>', 'text/html')
// send the email message
echo 'The message was sent successfully!';
echo 'Error sending email message';
See how simple is to work with inline attachments? This process requires only that a value of "inline" be passed to the corresponding "setDisposition()" method before sending the message to the specified recipients.
The rest of the script remains practically the same, so I'm not going to waste your time with pointless explanations. Instead, now that you've learned the first option for working with an inline attachment, in the following section I'm going to demonstrate how to embed the same image file into a message using the previously mentioned "embed()" method.
Now, click on the link below and read the next segment. We're almost finished!
blog comments powered by Disqus