Obviously, any modern email library must be able to attach files to messages, and naturally Swift Mailer isn't an exception. But what's really exceptional in this particular case is that the library includes a separate class that does this, not surprisingly called "Swift_Attachment." Nevertheless, to help you understand how to use this class a bit more clearly, below I developed another simple script. This time, it not only uses the methods that you learned before for sending the email message, but attaches an image file to it. Take a look at it: // example on sending a basic email message with Swift Mailer (uses the 'attach()' method)
// include required files require_once 'lib/swift_required.php';
// create the mail transport using the 'newInstance()' method $transport = Swift_SmtpTransport::newInstance('mail.domain.com', 25) ->setUsername('alejandro@domain.com') ->setPassword('password');
// 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('alejandro@domain.com' => 'Alejandro Gervasio')) // specify the To argument ->setTo(array('john@domain.com' =>' John Doe')) ->setCc(array('mary@domain.com' => 'Mary Jackson')) ->setBcc(array('susan@domain.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!') ->attach(Swift_Attachment::fromPath('image1.jpg'));
// send the email message if ($mailer->send($message)) { echo 'The message was sent successfully!'; } else { echo 'Error sending email message'; } The above example definitely looks much more interesting, right? As you can see, it uses the "Swift_Attachment" class along with its "fromPath()" method to attach a fictional image file to the message before sending it. In this particular example, the file being attached resides in the same location of the script, but it's also possible to specify a full path for the file. However, this feature will be covered in the next tutorial, so for the moment, focus your attention on the previous script and grasp its driving logic. Done? Good. Now that you've learned how to compose and send a message with an attached image file, the next thing I'm going to show you is Swift Mailer's capabilities for dispatching email in HTML format. This topic will be discussed in the last section of this tutorial. Therefore, click on the link that appears below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|