Send Mail through GMail SMTP Server with PHP

The HTML Mail app lets you send rich text emails to anyone without requiring an account. Internally, it uses the mail() function of PHP to deliver these messages.

The PHP Mailer library on Github is a wrapper over the built-in mail function but adds support for attachments and also integrates with SMTP so you can send mail without having a local mail server. This script lets you send messages via your Google’s Gmail server.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = '';                       // Specify main and backup server
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '';                   // SMTP username
$mail->Password = 'digitalinspiration';               // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
$mail->Port = 587;                                    //Set the SMTP port number - 587 for authenticated TLS
$mail->setFrom('', 'Amit Agarwal');     //Set who the message is to be sent from
$mail->addReplyTo('', 'First Last');  //Set an alternative reply-to address
$mail->addAddress('', 'Josh Adams');  // Add a recipient
$mail->addAddress('');               // Name is optional
$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/usr/labnol/file.doc');         // Add attachments
$mail->addAttachment('/images/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;

echo 'Message has been sent';