Sending e-mails via SMTP with PHPmailer and Gmail

These days I tried some plugin to send mail message within bbpress via SMTP. Since my domains email is hosted with Google applications I decided to send my messages via the SMTP server from Gmail. I found several articles and tutorials, but a lot of them didn’t worked for me.

Why using Gmail for sending mail messages?

First of all it’s FREE! Sure most website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use Gmail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day, check this information from the Google help pages.

Requirements

You need for this code example a PHP5 enabled web host (I tested only on Linux), the port 465 need to be open and of course you need a Gmail or Google applications account.

SMTP for Gmail tutorial

  1. If you don’t have one, register a Gmail account or setup your domain for Google applications.
  2. Download a recent version of PHPMailer (I used the version 5.02)
  3. Check with your web hosting provider if port 465 (TCP out) is open, if not ask him to open that port
  4. Include the phpmailer class file: require_once('phpmailer/class.phpmailer.php');
  5. Create those two constant variable to store your Gmail login and password. Use the login for your Google application mail if you have one.
    define('GUSER', 'you@gmail.com'); // Gmail username
    define('GPWD', 'password'); // Gmail password
  6. Use the following function to send mail messages (add the function in one of your included files):
    function smtpmailer($to, $from, $from_name, $subject, $body) { 
    	global $error;
    	$mail = new PHPMailer();  // create a new object
    	$mail->IsSMTP(); // enable SMTP
    	$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
    	$mail->SMTPAuth = true;  // authentication enabled
    	$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    	$mail->Host = 'smtp.gmail.com';
    	$mail->Port = 465; 
    	$mail->Username = GUSER;  
    	$mail->Password = GPWD;           
    	$mail->SetFrom($from, $from_name);
    	$mail->Subject = $subject;
    	$mail->Body = $body;
    	$mail->AddAddress($to);
    	if(!$mail->Send()) {
    		$error = 'Mail error: '.$mail->ErrorInfo; 
    		return false;
    	} else {
    		$error = 'Message sent!';
    		return true;
    	}
    }

    Most of the setting inside the function are required by Gmail. While searching for tutorials I found articles with different settings for the port and security. My advice use them as in this tutorial.

  7. Call the function within your code:
    smtpmailer('to@mail.com', '', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');

    Use this more “advanced” usage inside your application:

    if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
    	// do something
    }
    if (!empty($error)) echo $error;

Advanced setup with fall-back SMTP server

Because of the limit it might be useful to use a secondary SMTP server if the Gmail option didn’t send the message. For this functionality we need to replace the part with the smtp settings a little bit. First create login/server variables for the 2nd SMTP server:

define('SMTPUSER', 'you@yoursmtp.com'); // sec. smtp username
define('SMTPPWD', 'password'); // sec. password
define('SMTPSERVER', 'smtp.yoursmtp.com'); // sec. smtp server

Next we need to create a if/else statement using the variables for the second server (replace).

function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) { 
	global $error;
	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->SMTPAuth = true; 
	if ($is_gmail) {
		$mail->SMTPSecure = 'ssl'; 
		$mail->Host = 'smtp.gmail.com';
		$mail->Port = 465;  
		$mail->Username = GUSER;  
		$mail->Password = GPWD;   
	} else {
		$mail->Host = SMTPSERVER;
		$mail->Username = SMTPUSER;  
		$mail->Password = SMTPPWD;
	}        
	$mail->SetFrom($from, $from_name);
	$mail->Subject = $subject;
	$mail->Body = $body;
	$mail->AddAddress($to);
	if(!$mail->Send()) {
		$error = 'Mail error: '.$mail->ErrorInfo;
		return false;
	} else {
		$error = 'Message sent!';
		return true;
	}
}

And use the function now as followed:

$msg = 'Hello World';
$subj = 'test mail message';
$to = 'to@mail.com';
$from = 'from@mail.com';
$name = 'yourName';
 
if (smtpmailer($to, $from, $name, $subj, $msg)) {
	echo 'Yippie, message send via Gmail';
} else {
	if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
		if (!empty($error)) echo $error;
	} else {
		echo 'Yep, the message is send (after hard working)';
	}
}

Both examples are very simple and demonstrate only how-to send mail messages via the SMTP server from Gmail. Of course the user can extend the code to handle HTML messages and attachements etc. If you have any issues with these examples, just let me know. Post a comment here or post to our partner PHP script forum.

 

Related posts

Comments

Trackback URL for this post: http://www.web-development-blog.com/archives/send-e-mail-messages-via-smtp-with-phpmailer-and-gmail/trackback/

very nice post, thanks.

I havent tried it with goolge but you might want to have a look at zend framework mail classes. They have very nice api and a lot of functionality. To be honest i prefere to stick with zend as long as fulfills my needs ;-)

Thanks

Hi Artur,

you’re right I like the Zend Framework too.
Never user the mail class from them because I like phpmailer a lot. If you start a small website it’s much faster to use phpmailer. Do you have any experience about the “reach the inbox success” for the Zend SMTP mail class?

Just noticed that I forgot to use the Cc option inside the function. I removed it from the example

(this information is for people read the tutorial within the last 12 hours)

You have misstype in requirements,
port 465 it is Gmail server port and PHPMailer don’t need to open it on your server. You have set it as server settings in you class configuration.

So you need to verify possibility connections to this port on another server, not your server port.

PS:
port 465 is SMTPs port – secure SMTP

Hi Alexandr,

that’s right port 465 is needed by Gmail’s SMTP server. In my example script this port is only used for that server. The fall-back example is using the default SMTP Port: 25.

The requirements are related to sending mails via Gmail’s SMTP server.

Really cool tutorial. The best way to get into the inbox is not send mail from your own server, and let someone else deal with it.

That said, there are plenty of other factors that will will put your email in the spam folder. Reverse PTR, SPF Records, Domain Keys, and various mail headers are things that will still need to be set correctly for your email to make it to the Inbox.

hello Chris,

great that you like the tutorial.
You’re right without a SPF record it’s very risky even if you use Google Apps for your domain. check this information from the Google help:
http://www.google.com/support/a/bin/answer.py?hl=en&answer=33786

I suggest the function could return true in case of succcess, and the error message in case the email is not sent, so not global variable is used, and the outside code would be something like

if (($error = smtpmailer($to, $from, $name, $subj, $msg, false)) === true)
{
// Everything went fine
}
else
{
echo $error;
}

Nice addition lloyd27, thanks.

Sorry Olaf and lloyd27 my php isn’t fluent. Am I missing something? How is lloyd27’s call to the function attempting to send via gmail? He’s set the parameter $is_gmail to false.

Hi Jeff,

lloyd27’s snippet is just to demonstrate the error handling, it’s not related to the mail function in this tutorial.

The code like described works very well.

Hi,

Excellent article. I am often having problems with my shared host being blacklisted through genuine email distribution scripts on the accounts within it and this script looks like an excellent way around that.

Of interest, http://mxtoolbox.com/blacklists.aspx is a good resource for checking blacklist status if you’re having trouble sending, as I was.

Regards,

David McLeary
Emerging Innovations

Sorry, the comment form is closed at this time.