How to Send Email in PHP via Mail and SMTP

Sending out email notifications from any web app/mobile app is an integral part of communication to the customers. Notifications can be sent via different channels, such as email, SMS, WhatsApp or push notifications. 

Email server setup is one of the operations and development tasks that can be set up and executed using scripts written in JavaScript or PHP or any coding language that your web/mobile app supports.

Below is an illustration of how sending an email server works with SMTP protocol used by the email server hosted on the internet.

Php Working Block

SMTP protocol is nothing but the signal that connects your email software to a network. Network understands this sign or signal that it needs to forward the messages to recipients via IMAP/POP3 server.

In the illustration above, the email message travels through intermediaries to reach a destination. The communication protocol (SMTP) is what these intermediaries understand to pass on the message.

Each email service provider has a limit to send out a number of messages per connection. This message limit depends on SMTP that is used by the service provider. SMTP determines the limit of sending out email messages per connection.

Now, let us understand how the email process works with SMTP.

Email Communication (End-to-End Process)

  1. You open the browser and access your email account using Gmail or Outlook website. Create a message using the recipient’s email address, subject and message body and hit Send. The action is initiated from the email client and connects to the domain’s SMTP server, for example – smtp.outlook.com.

The property on the Windows server will look like this:

SMTP=smtp.outlook.com
  1. While connecting to smtp.outlook.com, the request is sent with the sender email address, message text and the recipient address.
  2. The SMTP takes the route further to reach out to the receiver’s domain with the message. There are two scenarios in this.
    • SMTP’s domain and Recipient’s domain server is the same – In this, no routing is needed between the servers.
    • SMTP’s domain and Receipt’s domain server are different. – In this, routing is needed to reach out to recipients DNS (Domain Name Server)
  3. In case of the second scenario above, the SMTP server searches for the receiver’s DNS and converts it to an IP address that is binded to the DNS. Once the IP address is determined by the SMTP server, the message is sent efficiently to the receiver’s SMTP.
  4. The recipient’s SMTP server recognizes the incoming message from DNS and the IP address and forwards the message to recipients IMAP/POP3 server. 
  5. The receiver’s email client processes the IMAP/POP3 request and the message is available in the recipient’s mailbox. 

Now, we will see how to send email in PHP.  

How to Send a text email in PHP

Before writing a script for sending an email in PHP, the first thing to do is to configure the php.ini file located in your /etc folder of PHP server. This is the hosting server where your application / website code is deployed. 

NOTE: It is recommended to download the repository on your local machine and make the changes. Once done, you can push your changes in Live.

You will get the SMTP connection details such as authentication credentials from your hosting service provider. In addition to that, please map your domain with SMTP server IP address as a part of DevOps setup. Mostly, the set up server is Apache server.

 Below parameters and values need to be set in the file.

  1. Configure the php.ini file in your Windows production server.
    • Open the file in notepad. Edit the parameters below.
    • Enter the SMTP server’s address as below.
    • Enter the email address from which the email to be sent.
SMTP=smtp.outlook.com
[email protected]

To setup the same on your local (DEV) environment,

  1. Enter the SMTP and port entries as below. NOTE: Remove semi-colon prior to the entry.
SMTP=smtp.outlook.com
smtp_port=587

Once configured, the next step is to use the sendmail() function in your testingsendmail.php file.

  1. Open notepad++. Name the file as testingsendmail.php.
  2. Enter the below code in the file. Below are the mandatory parameters for which the values should be available in the script.
<?php 
$to_email = '[email protected]';
$subject = 'Thank you for using our services';
$message = 'Your transaction is successful with {companyname}';
$headers = 'From:[email protected]';
mail($to_email,$subject,$message,$headers);
if(mail($to_email,$subject,$message,$headers)) 
{   
   echo “Your message is sent successfully.”;
} 
else {     
 echo “Sorry, we could not send this message.” ;
 }?>

NOTE: We have done exception handling by entering condition and show the error message if the message sending is NOT A SUCCESS.

  1. The output of the email will look like this:
Email

We have seen sending a simple text email. Now, let us see how we send a mail format in an HTML file embedding the PHP script.

Send HTML Email in PHP

To embed an PHP script in an HTML file, you will need to understand the MIME type that is used to format the text on your email. MIME’s full form is Multipurpose Internet Mail Extensions. 

You can configure the SMTP server as described in the section above. Follow the steps below to send an email using an HTML file.

  1. Create testingsendmail.html using notepad.
  2. The below code snippet is an HTML file in which PHP code is written to send email to the recipient(s). 
<html>   
   <head>  
    <title>An HTML eMail Format for your knowledge</title>   
</head>
      <body>      
      <?php         $to = "[email protected]";      
   $subject = "Thank you for using our services";  
                $message = "<b>Your transaction is successful with Tech4Net.</b>";    
     $message .= "<h1>Your Transaction Details: INR 25,000.</h1>";  
                $header = "From:[email protected] \r\n";   
      $header .= "Cc:[email protected] \r\n"; 
        $header .= "MIME-Version: 1.0\r\n";       
  $header .= "Content-type: text/html\r\n";      
            $setvalue = mail ($to,$subject,$message,$header);       
           if( $setvalue == true ) {        
    echo "Your message is sent successfully.";      
   }
else {     
       echo "Sorry, we could not send this message.";     
    }   
   ?>       
  </body>
</html>
  1. Save your HTML file and try sending email to check whether it is sent successfully.

Let us understand how to prevent spamming of emails that you get in the form of an inquiry form available on your website and you are auto-sending the reply to them as “thank you for your inquiry.”

To send secure email from your SMTP server, there are some validations written. The filter_var() function is used for validation of user data or inputs.

  1. Create testingsendmail.html using notepad.
  2. The below code snippet is an HTML file in which PHP code is written to validate an email before sending it to the recipient(s). 
<html>
      <head>
      <title>An HTML eMail Format for your knowledge</title>  
 </head>  
    <body>   
         <?php  
  function validate_email($fieldname) {  
  $fieldname = filter_var($fieldname, FILTER_SANITIZE_EMAIL);  
  if (filter_var($fieldname, FILTER_VALIDATE_EMAIL)) 
{       
 return true; 
   } 
else 
{   
   return false; 
   }
}
      
  $to = "[email protected]";    
     $subject = "Thank you for using our services";         
         $message = "<b>Your transaction is successful with Tech4Net.</b>";     
    $message .= "<h1>Your Transaction Details: INR 25,000.</h1>";            
      $header = "From:[email protected] \r\n";       
  $header .= "Cc:[email protected] \r\n";    
     $header .= "MIME-Version: 1.0\r\n";    
     $header .= "Content-type: text/html\r\n";    
              $setvalue = mail ($to,$subject,$message,$header);   
               if( $setvalue == true ) 
{        
    echo "Your message is sent successfully.";     
    }
else
 {     
       echo "Sorry, we could not send this message."; 
        }    
  ?>   
      </body>
</html>

Below are the in-built parameters used to validate recipients’ email address and send them securely.

  • The “SANITIZATION TYPE” parameter is applied on the field to check sanitization.
  • FILTER_VALIDATE_EMAIL – To check email address is valid or invalid. It returns false when email ID is invalid.
  • FILTER_SANITIZE_EMAIL – To eliminate/ignore unsupported characters from email addresses. For example info]@yourdomain.com. It will remove ] from the email
  • FILTER_SANITIZE_URL – To eliminate/ignore illegal characters from the email address. 
  • FILTER_SANITIZE_STRING  – To eliminate/ignore tags from the string or text.
  1. Save your HTML file and try sending email to check whether it is sent successfully and securely.

You can also send email using Gmail SMTP server with PHPMailer. Let us see a quick snapshot of the process to send email.

  1. Download PHPMailer library from https://github.com/PHPMailer/PHPMailer/releases
  2. Download the package as zip. Reference screenshot below.
PHPMailer
  1. Download the package as zip. Once downloaded, extract the zip.
PHPMaailer Files
  1. Locate the below files.
    • class.phpmailer.php, 
    • class.smtp.php, 
    • PHPMailerAutoload.php
  2. Create a new folder Mail → PHPMailer as a subfolder and copy all the 3 files in this subfolder.
  3. Create a new file, index.php in the Mail folder.
  4. Enter the code for Gmail SMTP server details, hostname, port, authentication parameters.
SMTP Connection
  1. Now, enter the email related information in the continuation of the code. Specify username and password of the gmail account you are using.
SMTP
  1. Specify the sender email address in setFrom, addAddress, addReplyTo fields.
  2. Then, specify the email format and text of the email.
EMail Setting
  1. Add a line below $mail = new PHPMailer; with $mail = isSMTP(); if you are using localhost.
  2. When you want to deploy in production, comment the line as //$mail = isSMTP();.
  3. Upload the PHPMailer and index.php file on your live server.
  4. Go to your gmail account. Check the below points.
    • Make sure your 2nd factor authentication is OFF in sign in security.
    • Allow the less secure app option as ON. 

After performing the above steps, you will be able to successfully send out auto-email from your gmail account.

Setting up an SMTP server and sending email using PHP script is a Joint Activity of DevOps and Developer team. 

You may also like:

How To Unarchive Gmail Emails – Archive

How to add POP/IMAP email with Gmail