How to send email using Gmail SMTP with PHP

Generally any web application needs to send the emails to the users when there registration for the verification purpose or any notifications to the users.

In this mechanism we would like to send the emails through Gmail SMTP Configuration.
This is very simple to configure the SMTP setting in php

Before going to the code you need
  1. Your working gmail account with password
  2. Gmail Host : smtp.gmail.com
  3. Gmail port : 465 or 587
  4. Protocol : ssl or  tls
For more details about Gmail SMTP server
Project Structure
|-Smtpmail
| |-classes
| | |-class.phpmailer.php
| | |-class.smtp.php
|-library.php
|-smtpgmail.php
First of all you need the class.phpmailer.php , class.smtp.php and library.php files
smtpgmail.php
 <?php  
 include "classes/class.phpmailer.php"; // include the class name  
 $mail = new PHPMailer(); // create a new object  
 $mail->IsSMTP(); // enable SMTP  
 $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only  
 $mail->SMTPAuth = true; // authentication enabled  
 $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail  
 $mail->Host = "smtp.gmail.com";  
 $mail->Port = 465; // or 587  
 $mail->IsHTML(true);  
 $mail->Username = "YOURUSERNAME@gmail.com";  
 $mail->Password = "YOURPASSWORD";  
 $mail->SetFrom("YOURUSERNAME@gmail.com");  
 $mail->Subject = "GMAIL SMTP MAIL WITH PHP";  
 $mail->Body = "Welcome to TechiesBadi Programming blog url is: http://techiesbadi.blogspot.in";  
 $mail->AddAddress("TOADDRESS@EXAMPLE.COM");  
  if(!$mail->Send()){  
      echo "Mailer Error: " . $mail->ErrorInfo;  
 }  
 else{  
      echo "Message has been sent";  
 }  
 ?>  
The above code change these fields to your credentials
YOURUSERNAME, YOURPASSWORD
And change the to address of this field TOADDRESS@EXAMPLE.COM

Download
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff


EmoticonEmoticon