Sending Mail Via Google's SMTP Server Using PHP

Aim
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.

Assumptions
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
Sofware/ComponentImage
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

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

 1. require("PHPMailer_v5.1/class.phpmailer.php");
 2. 
 3. 
 4. $mailer = new PHPMailer();
 5. $mailer->IsSMTP();
 6. $mailer->Host = 'ssl://smtp.gmail.com:465';
 7. $mailer->SMTPAuth = TRUE;
 8. 
 9. $mailer->Username = 'harrypotter@gmail.com';
10. $mailer->Password = 'alhamora';
11. 
12. $mailer->From = 'harrpotter@gmail.com';
13. $mailer->FromName = 'Harry Potter';
14. $mailer->Body = "Hello there all\nHow is everyone today?";
15. $mailer->Subject = "Hello from Harry";
16. 
17. $mailer->AddAddress(hermionegranger@hotmail.com);
18. $mailer->AddAddress(ronweasely@yahoo.com);
19. 
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

2 comments:

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.