As you’ll certainly know, any decent email library must have the ability to send copies of an email message to multiple recipients, and Swift Mailer isn’t an exception. Similar to the “From” argument, which was covered in previous examples, the library uses a method called “setCc()” to specify the MIME “Cc” header.
Let me show you a concrete example that uses this method to specify that a carbon copy of a sample message must be sent to a fictional recipient. The corresponding code sample looks like this:
// example on sending a basic email message with Swift Mailer (uses the 'setCc()' 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'))
// specify the Cc argument
->setCc(array('email@example.com' => 'Mary Jackson'))
// build the body part of the message
->setBody('Hey, how are you? I am sending you a message with the cool Swift Mailer library');
As I mentioned earlier, thanks to Swift Mailer’s intuitive API, it’s extremely easy to specify that a carbon copy of an email message has to be send to a different recipient. Of course, this is achieved by means of the “setCc()” method, which takes an array comprised of the recipient’s email address and their full name as an input argument. Simple to code and read, right?
As you may have noticed, though, the previous script is still incomplete. It does build the proper MIME headers, but it doesn’t actually send out any email messages. What’s the missing part? It’s necessary to call the already-familiar “send()” method to dispatch the corresponding emails.
Therefore, in the last section of this tutorial I’m going to list for you the complete code of the script, this time including the segment that really sends the email message, along with the carbon copy.
Now, go ahead and read the next few lines. We’re almost done!
blog comments powered by Disqus