Sending Emails in PHP (2 ways)

Wednesday 09th, Dec, 2015 | #



In this article we’ll talk about why you should use mail() function or PHPMailer for send email in php, and we’ll show some code samples on how to use it's

Using mail() function

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.

 <?php

function sendLocalEmail($subject, $body, $to) {

 $headers = "MIME-Version: 1.0" . "\r\n";
 $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
 $headers .= 'From: <'. $to .'>' . "\r\n";
 $headers .= 'Cc: [email protected]' . "\r\n";
 
 if(mail($to, $subject, $body, $headers))
 {
 $result = 'ok';
 } else {
 $result = 'error';
 }
 
 return $result;

}

//usage
echo sendLocalEmail("Test Email","<p>Hello</p>","[email protected]");

?>

Using phpmailer library

phpmailer is a full-featured email creation and transfer class for PHP, firts you new download the lasted version from https://github.com/Synchro/PHPMailer

Example with local mailserver

 <?php

require_once "PHPMailer_v5.1/class.phpmailer.php";

$mail = new PHPMailer;

$mail->From = "[email protected]";
$mail->FromName = "Full Name";

$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]"); //optional

//Address to which recipient will reply
$mail->addReplyTo("[email protected]", "Reply");

//CC
$mail->addCC("[email protected]");
//BCC
$mail->addBCC("[email protected]");

//Send HTML or Plain Text email
$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<i>Hello</i>";
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send()) 
{
 echo "Mailer Error: " . $mail->ErrorInfo;
} 
else 
{
 echo "Message has been sent successfully";
}

?>

Parameters for remote email server

 $mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to