How to Send an E-mail Using PHP and Gmail

By | February 6, 2010

It is not a secret, that most e-mails that are sent by PHP mail() function are not delivered due to spam filters enabled. Even if you pass all the necessary headers, your message is often delivered to SPAM folder and in fact will never be read. In order to avoid this, we will send e-mails using a free class and Gmail SMTP. You need to have a Gmail account to use this method, but I think it should not be a problem. You will also have to pass your Gmail password to this script.

First of all, we will need a class to send e-mails using SMTP. It can be obtained here. We will also need a Gmail account, that has SMTP enabled. Make sure to check your settings tab to enable SMTP (it is enabled by default, but it is better to check this once again).

Then we will use the following code:

$mail = new PHPMailer();
// Recipient’s e-mail address
$email=”**@la******.com”;
// Message text (may contain HTML)
$milo=”Some text comes here”;
$mail->Mailer = “smtp”;
$mail->Host = “ssl://smtp.gmail.com”;
$mail->Port = 465;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = “youraccount@gmail.com”; // SMTP username
$mail->Password = “yourpass“; // SMTP password

$webmaster_email = “yo*********@gm***.com”; //Reply to this email ID
$name=”Preferred Buyer”; // Recipient’s name
$mail->From = “yo*********@gm***.com”;
$mail->FromName = “Youraccount.com”; // Edit this to select “From” header
$mail->AddAddress($email, $name);
$mail->AddReplyTo($webmaster_email, “Youraccount.com”);
$mail->WordWrap = 70; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = “This is my test message”;
$mail->Body = $milo; //HTML Body
$mail->Send();

All you need to start using this free script is to set up your Gmail access information and compose a message. All the necessary headers will be created automatically.

This method allows to send e-mails with html links, as most e-mails sent using other methods are blocked by spamasassin, or similar anti spam software.