Send Email Using Gmail SMTP Server and Swift Mailer Library

Do you want to send your emails using Gmail SMTP server? When you use the SMTP server for your emails, there is a high chance of your emails going to the user’s inbox and not to the spam. SMTP server prevents your emails from being marked as spam. In this article, we study how to send email using the Gmail SMTP server and the Swift Mailer library.

As a site owner, you always want your email to go straight into the user’s inbox and not into the spam or junk. It increases the probability of the user reading your email and taking the action you wish for.

Why Need to Use SMTP Server?

For a website, it is normal to have a form that sends an email to users or administrators. It can be your newsletter, contact form, or registration process where you need to send an email as an acknowledgment.

PHP provides a mail() function for sending emails. However, if your server does not configure mail settings correctly then this method does not work. Another possibility is when you send emails using mail() method, it can end up in spam.

To overcome these 2 situations, you should use the SMTP server for sending your emails.

Using the Swift Mailer library, the user can use any SMTP server like Gmail, Sendgrid, Mandrill, or your own hosting-provided SMTP server for sending emails. In this tutorial, I choose a Gmail SMTP server.

Having said that, let’s take a look at how to use the Swift Mailer library for sending emails.

Swift Mailer Installation

In order to use the Swift Mailer library, you should have PHP version 7.2 or higher on your server. If you are using the older version then upgrade it to the latest PHP version. Most hosting providers like Bluehost upgrade the PHP version on request. You don’t need to invest your time to update the version.

Going ahead, I recommend using Composer to install the Swift Mailer library. Open the terminal in your project root directory and run the command:

composer require swiftmailer/swiftmailer

As we are going to use Gmail SMTP, you need to change some settings on your Google account. Login to your Google account and click on Account. Once you are on the Google Account page, click on Security. Scroll down to the bottom and you will find ‘Less secure app access’ settings. Set it to ON.

less-secure-apps

Send Email Using Gmail SMTP Server and Swift Mailer Library

At this stage, you are ready with the Swift Mailer library and you also changed the Gmail account settings. Now, you are good to go ahead.

Let’s say you have a file sendmail.php where you need to write a code that sends emails. Write the below code in your PHP file.

sendmail.php

<?php
require_once 'vendor/autoload.php';
 
try {
    // Create the Transport
    $transport = (new Swift_SmtpTransport('smtp.googlemail.com', 465, 'ssl'))
      ->setUsername('YOUR_GMAIL_USERNAME')
      ->setPassword('YOUR_GMAIL_PASSWORD')
    ;
 
    // Create the Mailer using your created Transport
    $mailer = new Swift_Mailer($transport);
 
    // Create a message
    $body = 'Hello, <p>Email sent through <span style="color:red;">Swift Mailer</span>.</p>';
 
    $message = (new Swift_Message('Email Through Swift Mailer'))
      ->setFrom(['FROM_EMAIL_ADDRESS' => 'FROM_NAME'])
      ->setTo(['RECEPIENT_1_EMAIL_ADDRESS'])
      ->setCc(['RECEPIENT_2_EMAIL_ADDRESS'])
      ->setBcc(['RECEPIENT_3_EMAIL_ADDRESS'])
      ->setBody($body)
      ->setContentType('text/html')
    ;
 
    // Send the message
    $mailer->send($message);
 
    echo 'Email has been sent.';
} catch(Exception $e) {
    echo $e->getMessage();
}

In the above code, I have passed the below values for Gmail SMTP server settings.

  • Google SMTP Server Address: smtp.googlemail.com
  • Gmail SMTP Port: 465
  • Encryption: ssl

Apart from these values, you need to change other placeholders like YOUR_GMAIL_USERNAME, YOUR_GMAIL_PASSWORD, etc.

After replacing all values, run this file on a browser. You should get the email in the inbox, not in the spam.

Send Single or Multiple Attachments in an Email

Sometimes you may need to send attachments in an email. Using Swift Mailer you can send single or multiple attachments as follows:

$message->attach(Swift_Attachment::fromPath(__DIR__. '/sample.png')); //absolute path for your attachment
$message->attach(Swift_Attachment::fromPath(__DIR__. '/sample-ebook.pdf'));

All you need to do is use attach method and pass the absolute path of the file you need to send as an attachment. Here I assume you need to send ‘sample.png’ and ‘sample-ebook.pdf’ as attachments.

So our final code is as follows.

sendmail.php

<?php
require_once 'vendor/autoload.php';
 
try {
    // Create the Transport
    $transport = (new Swift_SmtpTransport('smtp.googlemail.com', 465, 'ssl'))
      ->setUsername('YOUR_GMAIL_USERNAME')
      ->setPassword('YOUR_GMAIL_PASSWORD')
    ;
 
    // Create the Mailer using your created Transport
    $mailer = new Swift_Mailer($transport);
 
    // Create a message
    $body = 'Hello, <p>Email sent through <span style="color:red;">Swift Mailer</span>.</p>';
 
    $message = (new Swift_Message('Email Through Swift Mailer'))
      ->setFrom(['FROM_EMAIL_ADDRESS' => 'FROM_NAME'])
      ->setTo(['RECEPIENT_1_EMAIL_ADDRESS'])
      ->setCc(['RECEPIENT_2_EMAIL_ADDRESS'])
      ->setBcc(['RECEPIENT_3_EMAIL_ADDRESS'])
      ->setBody($body)
      ->setContentType('text/html')
      ->attach(Swift_Attachment::fromPath(__DIR__. '/sample.png'))
      ->attach(Swift_Attachment::fromPath(__DIR__. '/sample-ebook.pdf'))
    ;
 
    // Send the message
    $mailer->send($message);
 
    echo 'Email has been sent.';
} catch(Exception $e) {
    echo $e->getMessage();
}

It’s all about sending emails through the Swift Mailer library. You can also use Symfony Swift Mailer for sending messages via a few SMTP servers like Mailgun, Mandrill, etc. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “Send Email Using Gmail SMTP Server and Swift Mailer Library

Leave a Reply

Your email address will not be published. Required fields are marked *