Certainly, a good conclusion to this tutorial will demonstrate how flexible Swift Mailer can be for attaching files from different locations. In the next few lines Iím going to code another script, which will attach an image file from a specified URL that is not a local server.
Take a look at the following script:
// example on sending a basic email message with Swift Mailer (uses the 'addPart()' method and Swift_Attachment class and a URL for the attachment)
// 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('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';
There you have it. As you can see by the previous code sample, not only is it possible to send HTML email messages in a truly simple manner with Swift Mailer, but it makes attaching files from a remote server a breeze. What else can you ask for?
Well, much more actually. All of the examples developed so far showed how to attach files that have been created with an image editor. But what if the file that needs to be attached is generated dynamically with a graphic library? Is it possible to accomplish this with Swift Mailer?
Well, the answer is a resounding yes! But this topic and others will be covered in the section to come. Meanwhile, feel free to edit all the examples shown in this tutorial, to gain practice in working with file attachments.
Thatís all for the moment. In this seventh part of the series, I explained how to use the Swift Mailer library to attach files from different locations, including a remote host. In all of these cases, the ďfromPath()Ē method shown earlier allowed us to do this painlessly.
In the next article, Iím going to show you how to attach files that have been created dynamically, and change their names on the fly as well.
Donít miss the upcoming part!
blog comments powered by Disqus