Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; cronometro has a deprecated constructor in /home/wdrfree/public_html/model/admin/model.php on line 4
Sending Emails in PHP (2 ways) | wdrfree ▷

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.


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


echo sendLocalEmail("Test Email","<p>Hello</p>","");


Using phpmailer library

phpmailer is a full-featured email creation and transfer class for PHP, firts you new download the lasted version from

Example with local mailserver


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

$mail = new PHPMailer;

$mail->From = "";
$mail->FromName = "Full Name";

$mail->addAddress("", "Recepient Name");
$mail->addAddress(""); //optional

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


//Send HTML or Plain Text email

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

 echo "Mailer Error: " . $mail->ErrorInfo;
 echo "Message has been sent successfully";


Parameters for remote email server

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