Categories: PHP

Learn how to send Email From PHP with SwiftMailer

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 called 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:

  1. It does not support of authentication while sending email
  2. We can’t send an attachments of files with the email
  3. It’s doest work while sending an multiple emails in loop because it’s open and close the socket every time it send a email

Swift mailer features:

Advantages using swift mailer over mail function

  1. Support of SMTP authentication
  2. Support of HTML content email as well as file attachment
  3. We can request a read receipt – when recipient read the email after receiving
  4. 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 your on windows open command line else open terminal if your using linux or mac os. 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:
<?php

// 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:
<?php

// 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 support authentication with username and password it also supports encryption.

Create new `test_email.php` file and use following script:

<?php

// 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 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 exist.

<?php

// 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 needs 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.

<?php

// 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 alway subscribe from the subscription section it will keep you updated.

Yogesh Koli

Software engineer & Blogger lives in India, has 6+ years of experience working with the front-end and back-end web app development.

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example…

7 months ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify…

7 months ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter…

7 months ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the…

7 months ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them,…

7 months ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super…

7 months ago