Sending email using Gmail and Amazon SES SMTP Servers via PHPMailer

The ability to send email is one of the most desired and (sometimes) essential features for any modern Web Applications. From sending email for ‘Email Verification‘ to sendingĀ  Notifications, Invoices or Newsletter, it has so many usages.

I will discuss how to send email using PHP native function, its limitations and how to use PHPMailer to overcome these issues in this article. Moreover, I will also show how to email using Gmail and Amazon SES SMTP Servers via PHPMailer.

If you are looking to send Newsletter, here is article to Dynamically send MailChimp newsletter via PHP.

Sending Emails using PHP mail() function

You can use the PHP mail() function to send an email with PHP. It follows the following syntax:

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

The first three parameters ($to, $subject and $message) are mandatory while the remaining parameters are optional.

Even though you can use this function to send an email from the web server itself, it has some limitations. It is not suitable for larger volumes of email. It is less flexible and requires a local mail server to send out emails. Chances of getting mail in spam folder is high.

In addition to that, you need to construct message correctly before sending. Also, sending HTML-based emails and attachments is a nightmare.

 

Getting Started with PHPMailer

PHPMailer is a class library for PHP that provides a collection of functions to build and send email messages. It is one of the best alternatives to mail() function.

In order to use this library, download it from here. Copy the classes class.phpmailer.php and class.smtp.php to your project folder.

You can send using PHPMailer by using the following snippets.

require_once('path/to/library/class.phpmailer.php');

//PHPMailer Object
$mail = new PHPMailer;

$mail->SetFrom('from@domain','From Name');
$mail->Subject = 'Email Subject';

// Reciever email and name
$mail->AddAddress('to@domain', 'Receiver Name');
// Additional Reciver (optional)
$mail->addAddress("to@domain", "Receiver Name");

//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");

//Add CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Email Subject Text";
$mail->Body = "Body of Email";

// Now Send the mail
if($mail->Send()) {
  echo "Message sent!";
} else {
  echo "Mailer Error: " . $mail->ErrorInfo;
}


You can send attachment by adding the following code:

//Attachments
$mail->addAttachment('/var/tmp/tutorial.pdf');         // Add attachments
$mail->addAttachment('/tmp/tutorial.jpg', 'Tutorial');    // Optional name

SMTP with PHPMailer

PHPMailer’s integrated SMTP implementation allows email sending on various platforms without a local mail server. You can use the mail server of an another host to send email. You need to add and update the following snippets to use SMTP:

$mail->SMTPDebug = 2;                                 // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

To send email using Gmail SMTP, change the Host to ‘smtp.gmail.com’, port to ‘465’. Use your gmail account username and password to authenticate. Here’s the function:

define("SMTP_HOST", "smtp.gmail.com");
define("SMTP_PORT", 465);
define("SMTP_UNAME", "your_mail@gmail.com");
define("SMTP_PWORD", 'your password');


function google_mail($to, $subject, $message) {

    require('path_to_library/class.phpmailer.php');

    $mail = new PHPMailer;
    $mail->IsSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPDebug = 1;
    $mail->SMTPSecure = "ssl";
    $mail->Host = SMTP_HOST;
    $mail->Port = SMTP_PORT;
    $mail->Username = SMTP_UNAME;
    $mail->Password = SMTP_PWORD;
    
    $mail->SetFrom('From email','From Name');
    $mail->Subject = $subject;
    $mail->AddAddress($to, $subject);

    $mail->MsgHTML($message);
    $mail->IsHTML(true);
    $send = $mail->Send();
    return $send;
}

Now that you have code for sending email using Gmail SMTP, you can run it in your server. However, even with the correct credentials, you may still get the error like ‘ERROR:Password not accepted from server‘. Google’s servers block the server attempting to authenticate, as a security precaution.

Fixing Gmail ‘Password not accepted from server’ issue

In order to fix this issue, make sure you are logged in using the same Gmail account in your browser, and then simply go through this link.
https://accounts.google.com/b/0/DisplayUnlockCaptcha

This will take you to the page to allow authentication.

Gmail SMTP authentication

Click the Continue button to enable Account access. Now try sending email from your server. It should work.

Similarly, you can send email using Amazon SES SMTP. In order to do so, use appropriate value for host, port, username and password.

Host will be similar to ’email-smtp.us-east-1.amazonaws.com’ depending upon your Amazon SES account configuration.

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.