In the preceding part of this series, I explained how to attach a file to an email message via the “fromPath()” method of the “Swift_Attachment” class included with Swift Mailer. Below, you can study a short example that demonstrates how to perform this task. Examine the following code sample:
// example on sending a basic email message with Swift Mailer (uses the 'addPart()' method and Swift_Attachment class)
// 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 in HTML to make it look nicer</p>', 'text/html')
// send the email message
echo 'The message was sent successfully!';
echo 'Error sending email message';
The previous script not only uses the pertinent “fromPath()” method that belongs to the “Swift_Attachment” class to attach an image to a basic email message, but it also invokes another method, called “addPart().” As its name suggests, this methods allows you to add a new part to the message.
In this case, the part being annexed to the message is a single line of text formatted in HTML, which shows how easy it is to send HTML email with Swift Mailer.
Well, now that you’re familiar with the logic that drives the previous example, it’s time to explore other handy features of the library. Therefore, in the following section, I’m going to teach you how to use the “fromPath()” method to attach a file that resides on a different location on the web server.
Of course, the full details of this process will be covered in the upcoming segment, so read the next few lines.
blog comments powered by Disqus