Send Email in PHP using Gmail SMTP

Last modified on February 24th, 2017.

In this tutorial, let us see how to send email in PHP using PHPMailer library via Gmail SMTP. Sending email in PHP can be done with various mail transfer libraries available. For example,  PHPMailer, PEAR::Mail interface. These libraries provide advanced features like SMTP authentication and more.

Sending an email with PHP’s core function mail() is simpler. This function is too simple and lacks advanced features for sending an email. For example, we cannot send attachments using PHP’s mail().


In this tutorial, let’s use PHPMailer class for sending emails by using Gmail SMTP server. This library is popular because of its advanced features. Some of those features are,

  • Allows both plain text and HTML content as email body.
  • Allows array of email addresses for to|cc|bcc|reply-to.
  • It provides Secure/MIME encryption.
  • It supports various encoding techniques binary, base64 and etc.
  • It has multiple language support (English by default).
  • It provides email validation, SMTP authentication, word wrapping and more.

PHP Script for Sending Email using Gmail SMTP

For sending email using SMTP we need not have entire PHPMailer library. It is sufficient to have only class.phpmailer.php and class.smtp.php of this library.

We should set subject, content and header information. When we send email using Gmail SMTP make sure to set SMTPAuth as TRUE and SMTPSecure as tls/ssl. Use your Gmail  Username and Password to send an email.

$mail = new PHPMailer();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port     = 587;  
$mail->Username = "your gmail username";
$mail->Password = "your gmail password";
$mail->Host     = "";
$mail->Mailer   = "smtp";
$mail->SetFrom("Your from email", "from name");
$mail->AddReplyTo("from email", "PHPPot");
$mail->AddAddress("recipient email");
$mail->Subject = "Test email using PHP mailer";
$mail->WordWrap   = 80;
$content = "<b>This is a test email using PHP mailer class.</b>"; $mail->MsgHTML($content);
echo "Problem sending email.";
echo "email sent.";

For setting FromEmail and FromName, we can either use SetFrom() function or use PHPMailer properties PHPMailer::From and PHPMailer::FromName. For example,

$mail->From = "from email address";
$mail->FromName = "from name";

AddReplyTo(), AddAddress() functions will accept array of email addresses, and name is optional.

If we have HTML content as mail body, we need to set content body text/HTML by using,


After setting all properties and mailer information with the PHPMailer object, PHPMailer::send() function returns TRUE on successful mail transfer and FALSE on failure.

Download Email Script using GMAIL SMTP

Comments to “Send Email in PHP using Gmail SMTP”

Leave a Reply to Vincy Cancel reply

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

↑ Back to Top