How To Send Email Using PHPMailer and GMail

Hi there! Today we’ll be sending email using PHPMailer Library and your Gmail account. This code works even if you test it on your local machine (localhost) since the mailer server it uses is the Google mail server. You just have to be connected on the internet and you don’t have to install your own mailer server haha!

How To Send Email Using PHPMailer and GMail
Wanna send some mail?

You may download PHPMailer Library in this link: http://sourceforge.net/projects/phpmailer/

<?php
require("class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com';
$mailer->Port = 465; //can be 587
$mailer->SMTPAuth = TRUE;
// Change this to your gmail address
$mailer->Username = '[email protected]';
// Change this to your gmail password
$mailer->Password = 'yourpassword';
// Change this to your gmail address
$mailer->From = '[email protected]';
// This will reflect as from name in the email to be sent
$mailer->FromName = 'Your Name';
$mailer->Body = 'This is the body of your email.';
$mailer->Subject = 'This is your subject.';
// This is where you want your email to be sent
$mailer->AddAddress('[email protected]');
if(!$mailer->Send())
{
    echo "Message was not sent<br/ >";
    echo "Mailer Error: " . $mailer->ErrorInfo;
}
else
{
    echo "Message has been sent";
}
?>

If you want to add some attachments, just add a line something like this:

$mailer->AddAttachment('yourfolder/yourfile.gif');

For instant testing, you may download this code with the library files used and change the variables to your settings:



You can find more examples here.


Comments

5 responses to “How To Send Email Using PHPMailer and GMail”

  1. Anonymous Avatar
    Anonymous

    Very Nice…! Can you please show me how to send mails to several person, retrieving address fron database.

  2. 1. You should make this script as a function or method

    2. Retrieve those email addresses from the database

    3. loop through the data while calling the function with email address and other parameters passed

    ex. sendEmail($email, $name, $subj, $message);

  3. Anonymous Avatar
    Anonymous

    Doesn’t work. Tried with PHPMailer 5.2.0. Messages even appear in the Sent folder of my test Gmail account but they aren’t actually being sent.

  4. @Anonymous: Did you download my code? I’m not sure what PHPMailer version I used there. But it works in my end.

  5. Thank you so much for your post… Just so you know it helped me so much… thanks again… 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *