How to send emails in PHP using PHPMailer

We all know how to send out email using the mail() function in PHP. It asks for a few things like the recipient email address, subject, message text. Add to that the optional headers argument with which you can set the content type of the email, the sender email address, file attachments etc and you have a very nice and powerful function.

However limitations such as not being coder friendly and no support for SMTP authentication make it some what limited. Enter the PHPMailer.

PHPMailer is a PHP email transport class featuring file attachments, SMTP servers, CCs, BCCs, HTML messages, word wrap, etc. You can download it from here.

After downloading the files unzip it. I have downloaded PHPMailer_v5.1.zip for this purpose. After unzipping it you can use the class.phpmailer.php file in your code.

Please see following code snippet which uses PHPMailer to send out email in PHP

<?php
// Include the phpmailer class file
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
// SMTPAuth = true if using SMTP authentication otherwise set it to false
$mail->SMTPAuth = true;
// These 3 lines are not needed if SMTPAuth = false above
$mail->Host = "<mail_server_address>";
$mail->Username = "<authenticated_email_address>";
$mail->Password = "<authenticated_email_address_password>";  
// Set to true if sending HTML formatted email other wise set to false
$mail->IsHTML(false);
// The sender email address
$mail->From     = '<sender_email_address>';
// The sender name i.e. the one who is sending the email. This name will display on the email client of the recipient
$mail->FromName = '<sender_name>';
// The email subject
$mail->Subject  =  '<subject>';
// The email message body
$mail->Body     =  '<body_text>';
// The recipient email address
$mail->AddAddress('<recipient_email_address>', '');
if (!$mail->Send()) {
	// If there is an error then it prints out the error message here	
	echo $mail->ErrorInfo;
}
else {
        echo "Email sent successfully";
}
?>

Hope the above helped

Leave a Comment