Verification: a143cc29221c9be0

Php allows you to send emails directly from a script

What is PHP mail?

PHP mail is the built in PHP function that is used to send emails from PHP scripts.

The mail function accepts the following parameters;

  • Email address
  • Subject
  • Message
  • CC or BC email addresses
    • It’s a cost effective way of notifying users on important events.
    • Let users contact you via email by providing a contact us form on the website that emails the provided content.
    • Developers can use it to receive system errors by email
    • You can use it to email your newsletter subscribers.
    • You can use it to send password reset links to users who forget their passwords
    • You can use it to email activation/confirmation links. This is useful when registering users and verifying their email addresses

In this tutorial, you will learn-

  • Why/When to use the PHP mail
  • Simple Mail Transmission Protocol
  • Sanitizing email user inputs
  • Secure Mail

Why/When to use the mail PHP

Sending mail using PHP

The PHP mail function has the following basic syntax

  HERE,

  • “$to_email_address” is the email address of the mail recipient
  • “$subject” is the email subject
  • “$message” is the message to be sent.
  • “[$headers]” is optional, it can be used to include information such as CC, BCC
    • CC is the acronym for carbon copy. It’s used when you want to send a copy to an interested person i.e. a complaint email sent to a company can also be sent as CC to the complaints board.
    • BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses included in the BCC section will not be shown to the other recipients.

Simple Mail Transmission Protocol (SMTP)

PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.

On a hosted server, the SMTP settings would have already been set.

The SMTP mail settings can be configured from “php.ini” file in the PHP installation folder.

Configuring SMTP settings on your localhost Assuming you are using xampp on windows, locate the “php.ini” in the directory “C:\xampp\php”.

  • Open it using notepad or any text editor. We will use notepad in this example. Click on the edit menu

  • Click on Find… menu

  • The find dialog menu will appear

  • Click on Find Next button

  • Locate the entries
    • [mail function]
    • ; XAMPP: Don’t remove the semi column if you want to work with an SMTP Server like Mercury
    • ; SMTP = localhost
    • ; smtp_port = 25
    • Remove the semi colons before SMTP and smtp_port and set the SMTP to your smtp server and the port to your smtp port. Your settings should look as follows
      • SMTP = smtp.example.com
      • smtp_port = 25
      • Note the SMTP settings can be gotten from your web hosting providers.
      • If the server requires authentication, then add the following lines.
        • auth_username = This email address is being protected from spambots. You need JavaScript enabled to view it.
        • auth_password = example_password
        • Save the new changes.
        • Restart Apache server.

Php Mail Example

Let’s now look at an example that sends a simple mail.

Output:

  Note: the above example only takes the 4 mandatory parameters.

You should replace the above fictitious email address with a real email address.

Sanitizing email user inputs

The above example uses hard coded values in the source code for the email address and other details for simplicity.

Let’s assume you have to create a contact us form for users fill in the details and then submit.

  • Users can accidently or intentional inject code in the headers which can result in sending spam mail
  • To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.

Let’s create a custom function that validates and sanitizes the email address using the filter_var built in function.

Filter_var function The filter_var function is used to sanitize and validate the user input data.

It has the following basic syntax.

  HERE,

  • “filter_var(…)” is the validation and sanitization function
  • “$field” is the value of the field to be filtered.
  • “SANITIZATION TYPE” is the type of sanitization to be performed on the field such as;
    • FILTER_VALIDATE_EMAIL – it returns true for valid email addresses and false for invalid email addresses.
    •  FILTER_SANITIZE_EMAIL – it removes illegal characters from email addresses. info\@domain.(com) returns This email address is being protected from spambots. You need JavaScript enabled to view it..
    • FILTER_SANITIZE_URL – it removes illegal characters from URLs. http://www.example@.comé returns >http://www.example@.com
    • FILTER_SANITIZE_STRING  - it removes tags from string values. am bold becomes am bold.

The code below implements uses a custom function to send secure mail.

Output:

Secure Mail

Emails can be intercepted during transmission by unintended recipients.

This can exposure the contents of the email to unintended recipients.

Secure mail solves this problem by transmitting emails via Hypertext Transfer Protocol Secure (HTTPS).

HTTPS encrypts messages before sending them.

What is PHP mail?

PHP mail is the built in PHP function that is used to send emails from PHP scripts.

The mail function accepts the following parameters;

  • Email address
  • Subject
  • Message
  • CC or BC email addresses
    • It’s a cost effective way of notifying users on important events.
    • Let users contact you via email by providing a contact us form on the website that emails the provided content.
    • Developers can use it to receive system errors by email
    • You can use it to email your newsletter subscribers.
    • You can use it to send password reset links to users who forget their passwords
    • You can use it to email activation/confirmation links. This is useful when registering users and verifying their email addresses

In this tutorial, you will learn-

  • Why/When to use the PHP mail
  • Simple Mail Transmission Protocol
  • Sanitizing email user inputs
  • Secure Mail

Why/When to use the mail PHP

Sending mail using PHP

The PHP mail function has the following basic syntax

  HERE,

  • “$to_email_address” is the email address of the mail recipient
  • “$subject” is the email subject
  • “$message” is the message to be sent.
  • “[$headers]” is optional, it can be used to include information such as CC, BCC
    • CC is the acronym for carbon copy. It’s used when you want to send a copy to an interested person i.e. a complaint email sent to a company can also be sent as CC to the complaints board.
    • BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses included in the BCC section will not be shown to the other recipients.

Simple Mail Transmission Protocol (SMTP)

PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.

On a hosted server, the SMTP settings would have already been set.

The SMTP mail settings can be configured from “php.ini” file in the PHP installation folder.

Configuring SMTP settings on your localhost Assuming you are using xampp on windows, locate the “php.ini” in the directory “C:\xampp\php”.

  • Open it using notepad or any text editor. We will use notepad in this example. Click on the edit menu

  • Click on Find… menu

  • The find dialog menu will appear

  • Click on Find Next button

  • Locate the entries
    • [mail function]
    • ; XAMPP: Don’t remove the semi column if you want to work with an SMTP Server like Mercury
    • ; SMTP = localhost
    • ; smtp_port = 25
    • Remove the semi colons before SMTP and smtp_port and set the SMTP to your smtp server and the port to your smtp port. Your settings should look as follows
      • SMTP = smtp.example.com
      • smtp_port = 25
      • Note the SMTP settings can be gotten from your web hosting providers.
      • If the server requires authentication, then add the following lines.
        • auth_username = This email address is being protected from spambots. You need JavaScript enabled to view it.
        • auth_password = example_password
        • Save the new changes.
        • Restart Apache server.

Php Mail Example

Let’s now look at an example that sends a simple mail.

Output:

  Note: the above example only takes the 4 mandatory parameters.

You should replace the above fictitious email address with a real email address.

Sanitizing email user inputs

The above example uses hard coded values in the source code for the email address and other details for simplicity.

Let’s assume you have to create a contact us form for users fill in the details and then submit.

  • Users can accidently or intentional inject code in the headers which can result in sending spam mail
  • To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.

Let’s create a custom function that validates and sanitizes the email address using the filter_var built in function.

Filter_var function The filter_var function is used to sanitize and validate the user input data.

It has the following basic syntax.

  HERE,

  • “filter_var(…)” is the validation and sanitization function
  • “$field” is the value of the field to be filtered.
  • “SANITIZATION TYPE” is the type of sanitization to be performed on the field such as;
    • FILTER_VALIDATE_EMAIL – it returns true for valid email addresses and false for invalid email addresses.
    •  FILTER_SANITIZE_EMAIL – it removes illegal characters from email addresses. info\@domain.(com) returns This email address is being protected from spambots. You need JavaScript enabled to view it..
    • FILTER_SANITIZE_URL – it removes illegal characters from URLs. http://www.example@.comé returns >http://www.example@.com
    • FILTER_SANITIZE_STRING  - it removes tags from string values. am bold becomes am bold.

The code below implements uses a custom function to send secure mail.

Output:

Secure Mail

Emails can be intercepted during transmission by unintended recipients.

This can exposure the contents of the email to unintended recipients.

Secure mail solves this problem by transmitting emails via Hypertext Transfer Protocol Secure (HTTPS).

HTTPS encrypts messages before sending them.

PHP built-in mail function ()

There are two basic ways of sending emails with PHP: a built-in mail function and external mail packages.

PHP’s built-in mail function () is very simple, but it provides limited functionality for sending emails. You won’t be able to add attachments to your email, and building a beautiful HTML template with embedded images will be a tricky task as well. 

The other side of the PHP mail function () is that the email is sent from your web server, which may cause issues with deliverability due to security concerns such as suspicion of spam and blacklisting. The best way to overcome this problem is sending messages via an SMTP server, however, this functionality is limited as well. PHP mail() does not usually allow you to use the external SMTP server and it does not support SMTP authentication.

Here’s what you can do with PHP’s built-in mail function(): 

  • create simple HTML/text messages without attachments and images
  • send emails via localhost and Xmapp 
  • include several recipients with “$to” parameter. 

It is suitable for simple, mostly text-based notifications in your local environment. If you need to communicate with your app’s users, it is better to install an external mailer package.

If you are still committed to the PHP built-in mail function() and are ready to accept the challenge, let’s take a look at the basic code and its main parameters. 

Syntax and parameters

The PHP mail syntax is pretty simple:

It uses the following parameters: 

  • “$to” = your message recipient(s). The email address format may be user@example.com or User . In general, it needs to comply with RFC 2822.
  • “$subject” = your message’s subject
  • “$message” = the body of your message. Lines should be separated with a CRLF (\r\n). Each line should not exceed 70 characters.
  • “[$headers]” = additional recipients of your message, which can be included in CC or BCC. 

Note that headers are optional, except for the “from” header: it must be specified, otherwise, you will receive an error message like Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing.
You can use additional headers to change the mail “From” address and set the “Reply to” address.

For more details and additional parameters, refer to the PHP documentation.  

Sending HTML email using PHP mail() function

The body of the message can be written in HTML. However, as we’ve mentioned above, it should be simple. In the PHP mail function(), the HTML part will look like this:

$message = '


Review Request Reminder

Here are the cases requiring your review in December:

Case title Category Status Due date
Case 1 Development pending Dec-20
Case 1 DevOps pending Dec-21
';

It’s important to remember that to send HTML mail, you need to set the Content-type header:

$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';

Simple Transmission Protocol (SMTP)

Where do I specify the SMTP settings? This is a fair question. Go to the PHP installation folder and configure them in the “php.ini” file. But this will only work for localhost or Xmapp like solutions because as we have already mentioned,  PHP mail function does not support SMTP authentication and doesn’t allow sending messages via external servers. 

There are some other, rather haphazard options but we won’t promote them here. Alternatively, we recommend using external PHP mail packages for sending emails via an external SMTP server.

Sending multiple emails

To send your message to multiple recipients, specify their email addresses in “$to” =  parameter separating them with comma(-s).  It’s the only suitable method with a native mail() function. If you need to send a large volume of messages in a loop, try an external mailing package. In the official PHP documentation,  PEAR::Mail is recommended. 

PHP mailing packages

As we have already mentioned, the native PHP mail() function has limited functionality when it comes to mass sending. For example, it is not designed for creating engaging email templates that may boost your next campaign or sending a large volume of emails.

But since PHP is still one of the most popular programming languages, it also doesn’t lack resources for sending mass emails. Here are several plugins that we can highly recommend:

Pear Mail

Pear Mail is a class that provides multiple interfaces for sending emails (which is stated in their documentation). 

Here is what you can do with Pear Mail: 

  • create complex HTML/text messages with attachments and inlined images (with Mail_Mime class)
  • send emails via PHP’s built-in mail() function, a sendmail program, or SMTP server
  • send multiple emails from a queue (with Mail_Queue class).

Pear documentation looks a bit complicated but it’s still informative, and you can find several tutorials. To be able to compare several mail packages, let’s review code for sending a standard booking confirmation email. It will contain HTML and text parts, a single attachment, and will be sent via an authenticated SMTP server. 

For email experiments, we will use Mailtrap, a fake SMTP server. It imitates a real SMTP server and traps your test email in the virtual inboxes. This way, your email samples will never go to the inboxes of the real customers.

require_once './vendor/autoload.php';
$from = 'Your Hotel ';
$to = 'Me ';
$subject = 'Thanks for choosing Our Hotel!';

$headers = ['From' => $from,'To' => $to, 'Subject' => $subject];

// include text and HTML versions
$text = 'Hi there, we are happy to confirm your booking. Please check the document in the attachment.';
$html = 'Hi there, we are happy to 
confirm your booking. Please check the document in the attachment.'; //add attachment $file = '/confirmations/yourbooking.pdf'; $mime = new Mail_mime(); $mime->setTXTBody($text); $mime->setHTMLBody($html); $mime->addAttachment($file, 'text/plain'); $body = $mime->get(); $headers = $mime->headers($headers); $host = 'smtp.mailtrap.io'; $username = '1a2b3c4g5f6g7e'; // generated by Mailtrap $password = '1a2b3c4g5f6g7e'; // generated by Mailtrap $port = '2525'; $smtp = Mail::factory('smtp', [ 'host' => $host, 'auth' => true, 'username' => $username, 'password' => $password, 'port' => $port ]); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo('

' . $mail->getMessage() . '

'); } else { echo('

Message successfully sent!

'); }

Swift Mailer

Swift Mailer is another popular package for sending emails in PHP. It is feature-rich, well covered by documentation, and pretty straightforward in use.

Here is what you can do with Swift Mailer:

  • create complex HTML/multipart templates 
  • add attachments and embed images
  • send emails via authenticated SMTP, sendmail, Postfix, or your own transport
  • use additional plugins.

Besides that, Swift Mailer offers enhanced security and handles large attachments and images with low memory usage.

For more details, refer to the “How to Use Swift Mailer to Send Emails from PHP Apps” post. Below we will demonstrate a simple example of the same sending booking confirmation we used above.

setUsername('1a2b3c4d5e6f7g')
        ->setPassword('1a2b3c4d5e6f7g');

    $mailer = new Swift_Mailer($transport);

    // Create a message
    $message = new Swift_Message();

    $message->setSubject('Thanks for choosing Our Hotel!');
    $message->setFrom(['confirmation@hotel.com' => 'Your Hotel']);
    $message->addTo('me@gmail.com','Me');
    // Add attachment
   $attachment = Swift_Attachment::fromPath('./confirmations/yourbooking.pdf');
    $message->attach($attachment);

    // Set the plain-text part
    $message->setBody('Hi there, we are happy to confirm your booking. Please check the document in the attachment.');
     // Set the HTML part
    $message->addPart('Hi there, we are happy to 
confirm your booking. Please check the document in the attachment.', 'text/html'); // Send the message $result = $mailer->send($message); } catch (Exception $e) { echo $e->getMessage(); }

PHPMailer

And finally, PHPMailer, which is the classic and the most popular email sending library for PHP. It deserves a separate article and a tutorial. You will find it here.

Here is what you can do with PHPMailer:

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

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

Now let’s send our booking confirmation with PHPMailer:

isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = '1a2b3c4d5e6f7g';
$mail->Password = '1a2b3c4d5e6f7g’;
$mail->SMTPSecure = 'tls';
$mail->Port = 2525;

$mail->setFrom('confirmation@hotel.com', 'Your Hotel');
$mail->addAddress('me@gmail.com', 'Me');
$mail->Subject = 'Thanks for choosing Our Hotel!';
// Set HTML
$mail->isHTML(TRUE);
$mail->Body = 'Hi there, we are happy to 
confirm your booking. Please check the document in the attachment.'; $mail->AltBody = 'Hi there, we are happy to confirm your booking. Please check the document in the attachment.'; // add attachment $mail->addAttachment('//confirmations/yourbooking.pdf', 'yourbooking.pdf'); // send the message if(!$mail->send()){ echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; }