PHP | Send mail through Gmail SMTP server and phpmailer

|
| By Webner

We have mail() function to send emails in PHP. It uses built in sendmail command that uses local mail server to send emails. PHPMailer, on the other hand, is very different. Rather than relying on sendmail, it communicates directly with the SMTP server and relays the mail itself.

One of the main advantage of using SMTP over local server is that if you use mail() function to send mail with from address other than the name of the server then your mail will be marked as spam in the server of the person you are sending that mail.

Let’s see an example of sending emails using PHPMailer:

<?php
require_once('PHPMailer-master/class.phpmailer.php');
		include("PHPMailer-master/class.smtp.php");
include '../common/constants.php';
session_start();
class sendPdfViaEMail
{
function  sendemail($body1,$subject,$ccemail,$fromEmail,$bccEmail,$name,$to,$signature){
try {
	$mail             = new PHPMailer();
	if($name=="null")
	{
		$body.=$body1;	
	}
	else
	{
	$body.= "Dear $name,

"; $body.=$body1; $body .=$signature; } $mail->IsSMTP(); // tells the class to use SMTP $mail->Host = "smtp.gmail.com"; // SMTP server $mail->SMTPDebug = 2; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // enable SMTP authentication $mail->Host = "smtp.gmail.com"; // sets the SMTP server $mail->Port = 587; // sets the SMTP port for the GMAIL server $mail->Username = " xyz@test.com"; // SMTP account username $mail->Password = "abc123"; // SMTP account password $mail->SetFrom($fromEmail, 'DeDominic'); $mail->AddReplyTo($fromEmail,"DeDominic"); $mail->Subject = $subject; $mail->AltBody = "To view the message, please use a HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($body); $address = $to; $mail->AddAddress($address, "$name"); if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } }catch (phpmailerException $e) { print_R($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { print_R($e->getMessage()); } } } $obj=new SendPdfViaEMail(); $obj->sendemail();

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

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