How to send an email using PHPMailer

Home > Search > How-to
  by

PHPMailer is definitely a great solution to use when you want to send email using PHP. Download the PHP package from https://github.com/PHPMailer/PHPMailer.Extract the zip, and then move the extracted zip to your PHP web server.

 

To send an email with no authentication and no encryption.

<?php
   require "PHPMailerAutoload.php";
   $mail = new PHPMailer;
   $mail->isMail();
   $mail->Host = "mx1.example.com";
   $mail->Port = 25;
   
   $mail->setFrom("webmaster@example.com", "Webmaster");
   $mail->addAddress("John.Doe@example.com", "John Doe");
   $mail->addReplyTo("no-reply@example.com", "No Reply");

   $mail->Subject = "Here is the subject";
   $mail->Body    = "This is the message body";

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

 

To send an email with authentication and encryption.

<?php
   require "PHPMailerAutoload.php";
   $mail = new PHPMailer;
   $mail->isSMTP();
   $mail->Host = "mx1.example.com";
   $mail->SMTPAuth = true;
   $mail->Username = "user1";
   $mail->Password = "Password123";
   $mail->SMTPSecure = "tls";
   $mail->Port = 587;
   
   $mail->setFrom("webmaster@example.com", "Webmaster");
   $mail->addAddress("John.Doe@example.com", "John Doe");
   $mail->addReplyTo("no-reply@example.com", "No Reply");

   $mail->Subject = "Here is the subject";
   $mail->Body    = "This is the message body";

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

 


Debugging

If you run into problems, add the following to display verbose information.

$mail->SMTPDebug = 4;

 


Linux

If HTTPD is your web server, ensure HTTPD is configured to send email and network connect.

[root@server1 ~]# setsebool -P httpd_can_sendmail 1
[root@server1 ~]# setsebool -P httpd_can_network_connect 1

 

Verify both options are now on.

[root@server1 ~]# getsebool httpd_can_sendmail
httpd_can_sendmail --> on

[root@server1 ~]# getsebool httpd_can_network_connect
httpd_can_network_connect --> on

 

It's important to recognize that the PHP web server will be sending the email to the Email server. 

 

If a Linux web server is being used, such as Apache, HTTPD, or NGINX, the web server's SELinux context will need to allow PHP to send an email to the Email server. 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments