PHP: Send mail from Gmail/Zoho Mail using PHPMailer

In this tutorial, we will learn how to send email in PHP using Gmail and/or Zoho Mail's SMTP server.

With some clever setting of headers, the PHP mail() function can be used to send HTML emails (containing HTML tags along with CSS). However, it you want to test it on localhost, you will require to set up an extra mail server like Postfix, Sendmail, hMailServer, etc.

PHPMailer Github page

In most cases, the actual need is to configure to an already existing email account created in some email services like Yahoo Mail, Gmail, Outlook, Zoho Mail, etc. It could be your personal mail or one of your website's, but for such cases, it is much convenient to use some library with integrated external SMTP support like PHPMailer or Zend\Mail or SwiftMailer.

In this tutorial, we pick PHPMailer, one of the most popular email sending library for PHP. Originally developed by Brent R. Matzelle, it was first released in 2001. You can send HTML-based mails with attachments to multiple To, CC, BCC and Reply-to addresses. There is also a facility to send alternatve plain text to email clients which do not support HTML. Compatible with PHP 5.5 and above, it automatically validates email addresses and protects against header injection attacks. Its integrated external SMTP implementation allows you to do away with setting up a local mail server and you can trigger mails directly from your PHP project running on localhost.

To begin with, go to PHPMailer's official repository on Github and download the project ZIP file.

PHPMailer Github page

Extract/unzip the ZIP file and go inside its /src subdirectory. Copy the files PHPMailer.php, Exception.php and SMTP.php and place them at some convenient location in your project. In our example, we will place them in the same directory where the script file for sending mail is located. Include the following library files into it:

				
					require_once 'PHPMailer.php';
					require_once 'Exception.php';
					require_once 'SMTP.php';
				
			

Configuring PHPMailer to Send Email from Zoho Mail

You can use the below configuration to send mails from Zoho. It is useful especially if you have created your own custom email with your site's domain name in it, something like [email protected]. The SMTP settings are given here, with authentication over SSL (port 465) and TLS (port 587) respectively. We use SSL here, over port 465.

The IsHTML() method is passed the argument true so that the Body() method can contain HTML tags.

					
						$err = array();
						$mail = new PHPMailer\PHPMailer\PHPMailer();
						$mail->isSMTP();  // the mailer is set to use SMTP
						$mail->Host = "smtp.zoho.com";  // specify main and backup server
						$mail->SMTPAuth = true; // SMTP authentication is turned on
						$mail->Username = "[email protected]";  // SMTP username
						$mail->Password = ""; // SMTP password
						$mail->SMTPSecure = 'ssl'; 
						$mail->Port = 465;
						$mail->From = "[email protected]";
						$mail->FromName = "SCRIPTVERSE";	 // name is optional
						$mail->AddAddress('[email protected]');   
						$mail->AddReplyTo("[email protected]", "Hello");
						$mail->WordWrap = 50;  // set word wrap to 50 characters
						$mail->IsHTML(true); // set email format to HTML
						$mail->Subject = "Welcome to Scriptverse";
						$mail->Body    = "Hello Guest, <br/><br/> Welome to <b>ScriptVerse</b>. <br/></br/>Thank you,<br/>Scriptverse Team";
						$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
						if(!$mail->Send()) {
						   $err['mail'] = $mail->ErrorInfo;			
						}
					
				

The AltBody property is assigned plain text without any HTML tags to allow the user to read if his/her email client does not support HTML.

Configuring PHPMailer to Send Email from Gmail

For Gmail, there is a little tweaking to be done first: you need to enable the less secure app access ON here,

gmail less seure app access

and use the TLS server authentication over port 587.

We can add one more important line of code to see the state of connection while sending emails — the SMTPDebug property. There are five debugging levels: 0, 1, 2, 3 and 4, out of which 2 is the most useful one, as it prints messages sent by the client as well as those received from the server.

					
						$err = array();
						$mail = new PHPMailer\PHPMailer\PHPMailer();
						$mail->isSMTP();  // the mailer is set to use SMTP
						$mail->SMTPDebug = 1; // 1 - errors & messages; 2 - messages only
						$mail->Host = "smtp.gmail.com";  // specify main and backup server
						$mail->SMTPAuth = true; // SMTP authentication is turned on
						$mail->Username = "[email protected]";  // SMTP username
						$mail->Password = ""; // SMTP password
						$mail->SMTPSecure = 'tls'; 
						$mail->Port = 587;
						$mail->From = "[email protected]";
						$mail->FromName = "DENNIS GABIL";	 // name is optional
						$mail->AddAddress('[email protected]');   
						$mail->AddReplyTo("[email protected]", "Hello");
						$mail->WordWrap = 50;  // set word wrap to 50 characters
						$mail->IsHTML(true); // set email format to HTML
						$mail->Subject = "Hello from Dennis!";
						$mail->Body    = "Hello Friend, <br/><br/> Greetings! </br/>Thank you,<br/>Dennis";
						$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
						if(!$mail->Send()) {
						   $err['mail'] = $mail->ErrorInfo;			
						}
					
				

Below is the trail of messages left by the SMTPDebug property for level 1, for which you can substitute SMTP::DEBUG_CLIENT as well.

phpmailer smtp debug

The mail is sent to [email protected] (an ecommerce site that I have been building). It can be found in my Gmail account's /Sent folder.

gmail less seure app access