PHP has its own built in mail() function which is used to send emails. But it’s not flexible to use for sending emails as there is no guarantee about email delivery and it also take a lot of time to send email. There is one more disadvantage of this mail, that is most of emails goes to SPAM folder. To overcome these problems we have PHPMailer library. PHPMailer is world widely use tool for sending emails. Its very secure and easy to use.

Live DemoDownload

So let’s see how to integrate it on our PHP project.

First of all you need to grab your copy of PHPMailer from their official download page.

(You may also likeWhy to Choose PHP?)

Here is a small function that uses PHPMailer class, you can use it easily to send email. If you download my source file that I have given with this article. I have uses two main files. And one folder PHPMailer that basically contain PHPMailer library files. I have deleted all unwanted files from it and only take important files. So here is the way to use PHPMailer Class.

sendmail.php this file contain a simple function which uses PHPMailer to send emails. You have to call this function whenever you want to send email.

<?php
function send_mail($to, $body, $subject)
{
	require 'PHPMailer/PHPMailerAutoload.php';
	
	$mail = new PHPMailer;
	
	$mail->isSMTP();
	$mail->Host = 'smtp.gmail.com';
	$mail->SMTPAuth = true;
	$mail->Username = 'your gmail username@gmail.com';
	$mail->Password = 'your gmail password';
	$mail->SMTPSecure = 'ssl';
	$mail->Port = 465;
	
	$mail->From = 'your gmail username@gmail.com';
	$mail->FromName = 'Your Name';
	$mail->addAddress($to);
	$mail->addReplyTo('your gmail username@gmail.com', 'Reply');
	
	$mail->isHTML(true);
	
	$mail->Subject = $subject;
	$mail->Body    = $body;
	$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
	
	if(!$mail->send())
	{
		echo 'Message could not be sent.';
	} 
	else 
	{
		echo 'Message has been sent';
	}
}

?>

index.php here I have included above sendmail.php file so that I can call send_mail() function.

<?php

Include (“sendmail.php”);



$to = "user@example.com";

$body = "This is message body";

$subject = “This is Subject Example”;

send_mail($to, $body, $subject);

?>

Live DemoDownload

So this was the way to integrate PHPMailer on your own web server. If you have any type of query you can comment below. And if you like this tutorial don’t forget to subscribe us and share it with you friends 🙂

 

2 COMMENTS

  1. Thanks downloading now..is it a must to use a gmail account for the php mailer for sending the email and

Leave a Reply