
Today we are going learn about best PHP library called swiftmailer which is widely used by developers to send emails from PHP applications.
Before going to start working with the library let’s go through about its features, we can also call them advantages over regular PHP mail () function.
What is swiftmailer?
It’s a PHP library that is used to send emails from the PHP application; it’s a standalone component of Symphony framework meaning we can use independently in the PHP application
Limitations of PHP mail () function:
- It does not support of authentication while sending email
- We can’t send an attachment of files with the email
- It does not work while sending multiple emails in loop because it’s open and close the socket every time it sends an email
Swift mailer features:
Advantages using swift mailer over mail function
- Support of SMTP authentication
- Support of HTML content email as well as file attachment
- We can request a read receipt – when recipient read the email after receiving
- Good documentation support and easy to use
Installing Swift Mailer:
There are two ways to install the swift mailer in the PHP application that is using a PHP dependency manager called composer or downloading/cloning swiftmailer from its GitHub repository. I would prefer to use composer as a first choice if you don’t you have composer installed on your development environment you can go to getcomposer.org and click download link to access installation instruction according to your development environment.
Installing Swift Mailer with Composer:
If you’re on windows open command line else open terminal if you’re using Linux or macOS. Change your working directory using `cd` as showing below:
$ cd /var/www/php-email-sending-using-swiftmailer/
After navigating to the directory use following command to install swiftmailer package
$ composer require swiftmailer/swiftmailer @stable
Using above command composer is going to connect to the Internet and download package to our project directory and it will store under vendor directory.
You can see process here from the terminal:
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing swiftmailer/swiftmailer (v5.4.3)
Downloading: 100%
Writing lock file
Generating autoload files
Loading Swiftmailer into the php script:
If your with composer installation your easy to go if not don’t worry I will let you guide to load without using composer
- loading/including swiftmailer with composer autoloader:
// load composer packages
require __DIR__ . '/vendor/autoload.php';
only a single line will let you load all the packages you have installed thought composer, easy right?
- loading swiftmailer with swiftmailer required file:
// load swift mailer
require __DIR__ . '/vendor/swiftmailer/swiftmailer/lib/swift_required.php';
Example 1: Sending simple basic email with SMTP Server:
Swift mailer provides different classes to deliver emails, here we are going to use `Swift_SmtpTransport` which is going to provide us feature to connect to smtp server it supports authentication with username and password it also supports encryption.
Create new `test_email.php` file and use following script:
// load composer packages
require __DIR__ . '/vendor/autoload.php';
// SMTP server configuration
$smtp_server = 'smtp.example.com';
$username = 'user@example.com';
$password = 'YOUR-EMAIL-ACCOUNT-PASSWORD';
$port = '465';
$encryption = 'ssl';
// create message
$message = Swift_Message::newInstance()
->setSubject('Test Message Using SMTP Protocol!')
->setFrom(['user@example.com' => 'Admin'])
->setTo(['receiver@example.com' => 'Normal User'])
->setBody('This is Message body from Swift mailer SMTP test script!');
// create transport
$transport = Swift_SmtpTransport::newInstance($smtp_server, $port, $encryption)
->setUsername($username)
->setPassword($password);
// pass transport to the swift mailer
$mailer = Swift_Mailer::newInstance($transport);
// send email
$result = $mailer->send($message);
if ($result) {
echo "Message has been successfully sent!";
}
Example 2: Sending email with attachment:
It is impossible to send attachment with regular mail function or we can say it has lots of complications to do that, but by using swiftmailer we can get that in place in real easy way.
I am going to demonstrate on how we can attach a local file to the email.
Create new file ` test_attachment.php` and add following script to test attachment email, don’t forgot the add proper file address to be attach and make sure the specified file is there.
// load composer packages
require __DIR__ . '/vendor/autoload.php';
// SMTP server configuration
$smtp_server = 'smtp.example.com';
$username = 'user@example.com';
$password = 'YOUR-EMAIL-ACCOUNT-PASSWORD';
$port = '465';
$encryption = 'ssl';
// create message
$message = Swift_Message::newInstance()
->setSubject('Attachment Test Message Using SMTP Protocol!')
->setFrom(['user@example.com' => 'Admin'])
->setTo(['receiver@example.com' => 'Normal User'])
->setBody('This is Message body from Swift mailer SMTP test with Attachment script!');
// add attachment here
$attachment = Swift_Attachment::fromPath('something-to-attache.txt'); // set the file to be attached
$attachment->setFilename('File name'); // you can specify a file name here
$message->attach($attachment);
// create transport
$transport = Swift_SmtpTransport::newInstance($smtp_server, $port, $encryption)
->setUsername($username)
->setPassword($password);
// pass transport to the swift mailer
$mailer = Swift_Mailer::newInstance($transport);
// send email
$result = $mailer->send($message);
if ($result) {
echo "Message has been successfully sent!";
}
Example 3: HTML Email with Attachment:
I always see this is widely used email type in the project, every time we need to send email with a proper design format along with the links and attachments.
What I did here is create a `email.html` file with the html design and dummy content.
Keep in mind, when sending an HTML email, you should always include a plain text version of the email, that is exactly same content of the email but without html formatting. So, I have added plain_text.txt file as well along with simple plain text to be send.
Let get started:
Download Required files to use while sending html email from the link below:
Download HTML and Plain Text Files to Send Email
Next, I am going to use same local file that we had used for attachment example, you can use whatever you want.
Finally use this script to send our email, keep focus on the lines where I am getting the content from the file and using those variables while creating the message instance.
// load composer packages
require __DIR__ . '/vendor/autoload.php';
// SMTP server configuration
$smtp_server = 'smtp.example.com';
$username = 'user@example.com';
$password = 'YOUR-EMAIL-ACCOUNT-PASSWORD';
$port = '465';
$encryption = 'ssl';
// get html file content
$html_content = file_get_contents('email.html');
// get plain text
$plain_text = file_get_contents('plain_text.txt');
// create message
$message = Swift_Message::newInstance()
->setSubject('HTML Email Test!')
->setFrom(['user@example.com' => 'Admin'])
->setTo(['receiver@example.com' => 'Normal User'])
->setBody($html_content, 'text/html') // add html content
->addPart($plain_text, 'text/plain'); // Add plain text
// add attachment here
$attachment = Swift_Attachment::fromPath('something-to-attache.txt'); // set the file to be attached
$attachment->setFilename('File name'); // you can specify a file name here
$message->attach($attachment);
// create transport
$transport = Swift_SmtpTransport::newInstance($smtp_server, $port, $encryption)
->setUsername($username)
->setPassword($password);
// pass transport to the swift mailer
$mailer = Swift_Mailer::newInstance($transport);
// send email
$result = $mailer->send($message);
if ($result) {
echo "Message has been successfully sent!";
}
I hope this tutorial helps you to get your email sending working, if you still getting issues let me know in the comments below, I always try to respond comments and email as quickly as possible.
Happy coding, thanks for being a valuable member of iTech Empires, if you want to receive notification about new topics get uploaded here you can always subscribe from the subscription section it will keep you updated.