Sending Emails in PHP (2 ways)

Wednesday 09th, Dec, 2015 | #PHP


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: myemailcc@mydomain.com' . "\r\n";
 
 if(mail($to, $subject, $body, $headers))
 {
 $result = 'ok';
 } else {
 $result = 'error';
 }
 
 return $result;

}

//usage
echo sendLocalEmail("Test Email","<p>Hello</p>","recepient@domain.com");

?>

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 = "from@yourdomain.com";
$mail->FromName = "Full Name";

$mail->addAddress("recepient1@domain.com", "Recepient Name");
$mail->addAddress("recepient1@domain.com"); //optional

//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");

//CC
$mail->addCC("cc@domain.com");
//BCC
$mail->addBCC("bcc@domain.com");

//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 = 'user@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to