Sending Mail Via Google's SMTP Server Using PHP

We will create a simple php application that uses PHPMailer to connect to Google's smtp server to send out an email. You can use this for any email provider who allows SMTP access. This is useful from an e-commerce point of view, to send out emails that will not go straight into the recipients junk mail inbox. This method is preferred over sendmail which uses and SMTP relay. If you are hosting your application on a shared host, using PhpMailer will get around email limits set for sendmail by your hosting provider.

This article assumes that you have a compatible version of PHP installed and configured and you have downloaded and unzipped the PHPMailer

Versions used in this example
Windows XP SP2N/A
Php 5.2.12N/A
PhpMailer 5.1N/A
Links to these files can be found here.

For the purposes of this example PhpMailer has been unzipped in the diretory where the example script resides

As you can see we're connecting to google's SMTP server via the url ssl:// You have to login with a valid gmail username and password.

 1. require("PHPMailer_v5.1/class.phpmailer.php");
 4. $mailer = new PHPMailer();
 5. $mailer->IsSMTP();
 6. $mailer->Host = 'ssl://';
 7. $mailer->SMTPAuth = TRUE;
 9. $mailer->Username = '';
10. $mailer->Password = 'alhamora';
12. $mailer->From = '';
13. $mailer->FromName = 'Harry Potter';
14. $mailer->Body = "Hello there all\nHow is everyone today?";
15. $mailer->Subject = "Hello from Harry";
17. $mailer->AddAddress(;
18. $mailer->AddAddress(;
20. if(!$mailer->Send()) {
21.     error_log("Mailer :  error ".$mailer->ErrorInfo)." : $to";
22.     echo "fail";
23. }
24. else {
25.     echo "sent";
26. }
Hide line numbers


Anonymous said...

you also have to uncomment this line in your php.ini file:

extension=php_openssl.dll .
This will enable ssl support in php.

anti spam service said...
This comment has been removed by a blog administrator.