How to send emails in PHP

How to send emails in PHP

Listing few easy methods on how to send emails in php.

  • The first method is to use php default function to send email as described below.
<?php
    $to      = 'nobody@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: webmaster@example.com'       . "\r\n" .
                 'Reply-To: webmaster@example.com' . "\r\n" .
                 'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
  • The other commonly used way is PHPMailer

PHPMailer is the classic and the most popular email sending library for PHP. It deserves a separate article and a tutorial.

What you can do with PHPMailer

  • create complex HTML/multipart templates
  • add attachments and embedded images
  • send email from authenticated SMTP. 

PHPMailer is protected against header injection attacks and automatically validates emails. 

First install the library using below command

composer require phpmailer/phpmailer

Include packages and files for PHPMailer and SMTP protocol:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

Then use below code snippest to send email. Replace with your smtp details and subject ,body content.

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = "smtp";

$mail->SMTPDebug  = 1;  
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
$mail->Username   = "your-email@gmail.com";
$mail->Password   = "your-gmail-password";

$mail->addAttachment('/tmp/image.jpg', 'image.jpg');
$mail->IsHTML(true);
$mail->AddAddress("recipient-email@domain", "recipient-name");
$mail->SetFrom("from-email@gmail.com", "from-name");
$mail->AddReplyTo("reply-to-email@domain", "reply-to-name");
$mail->AddCC("cc-recipient-email@domain", "cc-recipient-name");
$mail->Subject = "Email using PHP Mailer";
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->Send()) {
  echo "Error while sending Email.";
  var_dump($mail);
} else {
  echo "Email sent successfully";
}

This is how you can send mail in php. Hope this will be helpfull.