Send Email using GMail SMTP server in PHP

PHP

This tutorial was suggested by SWDS. To send an e-mail using GMail’s SMTP server, you need extra help. Download the latest version of Swift Mailer Package from here.

This mailing class is simple, that’s why I recommend you to use Swift Mailer.
If you have enabled application specific password feature on Google Accounts, you may have to generate a new application password and use that password for SMTP authentication. Otherwise the example won’t be able to login to your google account.

<p>
  Let&#8217;s get started.
</p>

Create a file named send.php :

ini_set(“display_errors”,1);
require_once ‘../path/to/lib/swift_required.php’;
// Configuration
$transport = Swift_SmtpTransport::newInstance(‘ssl://smtp.gmail.com’, 465)
    ->setUsername(‘[email protected]‘) // Your Gmail Username
    ->setPassword(‘my_secure_gmail_password‘); // Your Gmail Password
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance(‘Wonderful Subject Here’)
    ->setFrom(array(‘[email protected]‘ => ‘My Name‘)) // can be $_POST[’email’] etc…
    ->setTo(array(‘[email protected]‘ => ‘A guy‘)) // your email / multiple supported.
    ->setBody(‘Here is the message itself. It can be text or

HTML

.’, ‘text/html’);
if ($mailer->send($message)) {
    echo ‘Mail sent successfully. Time to celebrate’;
} else {
    echo ‘Some error occurred. Check your configuration’;
}

The above example has configured with the following credentials :

Username          : [email protected]
Password           : my_secure_gmail_password
Send From         : [email protected]
Sender Name     : My Name
Receiver             : [email protected]
Receiver Name   : A guy

You should change the credentials to meet your conditions. If the mailing didn’t work, make sure the configuration is correct. If there’s any problems/suggestion/feedback just echo out in the comment box below.