As you know, there are cases where it’s necessary to attach a file that has been created dynamically to an email message, usually through a PHP server-side graphic library such as GD or via a custom function or class. Fortunately, Swift Mailer supports this requirement; its “fromPath()” method can take a file generated like this and annex it to an existing message. To demonstrate this ability, below I modified the script built in the previous section, which simulates the situation described above. Look at it: // example on sending a basic email message with Swift Mailer (uses the 'addPart()' method and Swift_Attachment class and attaches dynamic content)
// 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 // $image has been generated previously using for instance the GD library or a similar package $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!') ->addPart('<p>This part of the message has been formatted as HTML to make it look nicer</p>', 'text/html') ->attach(Swift_Attachment::newInstance($image, 'sample_image.png'));
// send the email message if ($mailer->send($message)) { echo 'The message was sent successfully!'; } else { echo 'Error sending email message'; } Even though at first sight the above script looks very similar to the one that you saw in the previous section, it actually performs a different task. It attaches a dynamic PNG file that has been hypothetically created with the GD PHP library. This file in question is then passed directly to the “newInstance()” method of the pertinent “Swift_Attachment” class, where it’s finally attached to the email message. Not too difficult to understand, right? Please don’t get me wrong; I don’t want to sound like I’m marketing the Swift Mailer library to you, but it definitely makes handling attachments a no-brainer process. However, I’d like to finish this tutorial by showing you yet another example; it will demonstrate how to change, on the fly, the name of a file being attached. To see how this last example will be created, read the next section. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|