In this article, we're going to explore the Swift Mailer library that allows you to send emails from PHP applications. Starting with installation and configuration, we'll go through a real-world example that demonstrates various aspects of sending emails using the Swift Mailer library.
What is Swift Mailer?
When it comes to sending emails in PHP applications, there are plethora of options to choose from. You might even end up creating your own wrapper to setup email features quickly. However, you're always in luck if you're using a well maintained and a feature-rich library.
The Swift Mailer is a popular library for sending emails from PHP applications, and is widely accepted by the PHP community. It's a feature-rich library in the sense that it covers almost every aspect of sending emails: from setting up different transports to customizing the message that's being sent.
In fact, it's a pretty straightforward process to send emails using the Swift Mailer library.
- initialize the Transport (SMTP/Sendmail) object
- initialize the Mailer object with that Transport
- initialize the Message object
- format and send the message
In the next section, we'll go through a real world example to demonstrate each of the aforementioned steps.
Installation And Configuration
In this section, we'll go through installation and configuration of the Swift Mailer library. The instillation is pretty straightforward, as it's already available as a Composer package. Before we go ahead, make sure you've installed the Composer because we'll need it to install the Swift Mailer library.
Once you've installed the Composer, go ahead and grab the Swift Mailer library using the following command.
$composer require "swiftmailer/swiftmailer:^6.0"
With that, the Swift Mailer library should be installed, along with the necessary dependencies in the vendor directory. And the contents of the newly created composer.json should look like this:
{ "require": { "swiftmailer/swiftmailer": "^6.0" } }
So, that's the installation part, but how are you supposed to use it? In fact, it's just a matter of including the autoload.php file created by Composer in your application as shown in the following snippet.
<?php require_once './vendor/autoload.php'; // your application code... ?>
How to Send Mails
In the earlier section, we explored how to install the Swift Mailer library using Composer. In this section, we'll start implementing a real world example.
Go ahead and create the email.php file with the following contents.
<?php require_once './vendor/autoload.php'; try { // Create the SMTP Transport $transport = (new Swift_SmtpTransport('smtp.hostname', 25)) ->setUsername('xxxxxxxx') ->setPassword('xxxxxxxx'); // Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport); // Create a message $message = new Swift_Message(); // Set a "subject" $message->setSubject('Demo message using the SwiftMailer library.'); // Set the "From address" $message->setFrom(['sender@gmail.com' => 'sender name']); // Set the "To address" [Use setTo method for multiple recepients, argument should be array] $message->addTo('recipient@gmail.com','recipient name'); // Add "CC" address [Use setCc method for multiple recepients, argument should be array] $message->addCc('recipient@gmail.com', 'recipient name'); // Add "BCC" address [Use setBcc method for multiple recepients, argument should be array] $message->addBcc('recipient@gmail.com', 'recipient name'); // Add an "Attachment" (Also, the dynamic data can be attached) $attachment = Swift_Attachment::fromPath('example.xls'); $attachment->setFilename('report.xls'); $message->attach($attachment); // Add inline "Image" $inline_attachment = Swift_Image::fromPath('nature.jpg'); $cid = $message->embed($inline_attachment); // Set the plain-text "Body" $message->setBody("This is the plain text body of the message.\nThanks,\nAdmin"); // Set a "Body" $message->addPart('This is the HTML version of the message.<br>Example of inline image:<br><img src="'.$cid.'" width="200" height="200"><br>Thanks,<br>Admin', 'text/html'); // Send the message $result = $mailer->send($message); } catch (Exception $e) { echo $e->getMessage(); }
Let's go through how this code works.
Initialize Swift Mailer
The Swift Mailer library supports different transports like SMTP and Sendmail while sending an email. So, the first thing that you need to do is to initialize the transport
object.
In the above example, I've used the SMTP transport to send mails.
$transport = (new Swift_SmtpTransport('smtp.hostname', 25)) ->setUsername('xxxxxxxx') ->setPassword('xxxxxxxx');
Of course, if you would like to use the Sendmail protocol, you'll need to initialize the corresponding Swift_SendmailTransport
object.
// Create the SendMail Transport $transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');
Once the transport is created, we need to initialize a mailer object and pass the transport that we've created already.
// Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport);
Create a Message
After creating the transport and mailer objects, the only remaining thing is to instantiate the Swift_Message
object and decorate it with necessary attributes.
// Create a message $message = new Swift_Message();
Now, we'll use the $message
object to prepare contents of our message. To start with, the setSubject
method allows you to set the subject of the email.
// Set a "subject" $message->setSubject('Demo message using the SwiftMailer library.');
The setFrom
method is used to set the from address of the email.
// Set the "From address" $message->setFrom(['sender@gmail.com' => 'Sender Name']);
Moving ahead, let's set the To address of the email. In fact, there are couple of variations for setting recipients of the email. If you want to set a single recipient, you can use the addTo
method and the setTo
method on the other end is used to set multiple recipients.
// Set the "To address" [Use setTo method for multiple recepients, argument should be array] $message->addTo('recipient@gmail.com','receiver name');
The addCc
and addBcc
methods are used to set the CC and BCC addresses of the email respectively.
// Add "CC" address [Use setCc method for multiple recepients, argument should be array] $message->addCc('recipient@gmail.com', 'recipient name'); // Add "BCC" address [Use setBcc method for multiple recepients, argument should be array] $message->addBcc('recipient@gmail.com', 'recipient name');
Attaching Files
Next, let's have a look at how you can attach a file to an email.
You first need to instantiate the Swift_Attachment
object with a valid filename. After creating the attachment object, you can add it to the email with the attach
method. Also, you can use the setFilename
method if you want to change the filename that will appear in the message attachment.
// Add an "Attachment" (Also, the dynamic data can be attached) $attachment = Swift_Attachment::fromPath('example.xls'); $attachment->setFilename('report.xls'); $message->attach($attachment);
Along with regular file attachments, sometimes you want to embed images in the message text. You can do that by using the embed
method as shown in the following snippet. The embed
method returns the unique ID of the embedded object, which you can use later on in the message while referencing the image via src
property.
// Add inline "Image" $inline_attachment = Swift_Image::fromPath('nature.jpg'); $cid = $message->embed($inline_attachment);
The Message Body
Next, let's set the email body by using the setBody
method.
// Set the plain-text "Body" $message->setBody("This is the plain text body of the message.\nThanks,\nAdmin");
If you want to set the HTML version of the message, you can use the addPart
method as shown in the following snippet. As you can see, we're using $cid
to reference the image we embedded earlier.
// Set a "Body" $message->addPart('This is the HTML version of the message.<br>Example of inline image:<br><img src="'.$cid.'" width="200" height="200"><br>Thanks,<br>Admin', 'text/html');
Send the Message!
Finally, we'll use the send
method of the Mailer object to send the email.
// Send the message $result = $mailer->send($message);
Try running the script, and you should receive an email! Let me know in the comment section if you face any issues.
Conclusion
Today, we looked at one of the most popular PHP libraries for sending emails: Swift Mailer. With this library, you can effortlessly send emails from your PHP scripts.
Feel free to post your thoughts and queries using the form below.
No comments:
Post a Comment