Blog

Guide: How to send emails in PHP (with examples)

Šarūnas Ročevas Šarūnas Ročevas
· 13 min read · Tips and resources · June 28th, 2023
PHP is a popular way to create dynamic web apps and send transactional emails. Learn how you can send different types of emails using the PHP mail() function as well as with MailerSend’s email API.

PHP is a modern and powerful open-source scripting language with a large, active community. It’s widely used in web development, including for the purpose of sending emails from websites and apps. There are several ways to send emails in PHP, but not all offer the same functionality or are optimized for sending best practices!

This guide will teach you how to set up PHP and configure your server to send and receive emails. We'll also show you actual code examples for different use cases to help you get started. You'll be able to start sending emails in PHP from your web app in no time.

Ready? Let's go!

Why use PHP to send emails

PHP is a fast, reliable and flexible way to send emails from a web server, making it the ideal solution for transactional email. 

Additionally, using PHP to send emails allows you to take advantage of the many email libraries and integrations built around it. These libraries usually provide advanced solutions such as email validation, spam protection and email tracking, making it easier to manage your transactional email.

Methods for sending emails in PHP

There are a few methods that you can use to send emails with PHP which can be divided into two categories: Using the built-in PHP mail() function and using email libraries.

1. Using the PHP mail() function

PHP's built-in mail() function is one of the simplest ways to send emails directly from the web server itself. It just takes three mandatory parameters: the email address, email subject and message body—and sends it to the recipient.

In order to send emails using this function, you need to make sure that your web server is properly configured. This involves installing a mail server such as Sendmail, Postfix or Qmail, and setting it up to send emails from your website.

If you use Linux or Unix, you can use the Sendmail or Qmail programs to send emails. If you use Windows, you can use the Sendmail program. Let’s take a look at how to configure Sendmail. 

You’ll first need to correctly configure the php.ini file with details of how you send email.

  1. Locate the php.ini file in the /etc/ directory and find the [mail function] section. 

  2. For Windows systems, you’ll need to define the SMTP parameter, which will point to your email server. And the sendmail_from parameter which should be your email address. It should look like this:

[mail function]
; For Win32 only.
SMTP = smtp.mailersend.net

; For win32 only
sendmail_from = hello@mailersend.com

For Linux or Unix, you’ll need to set the sendmail_path parameter to point to the executable file so that PHP knows where to find the Sendmail application. It will look like this:

[mail function]
; For Win32 only.
SMTP = 

; For win32 only
sendmail_from = 

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Notice the Windows parameters are left blank.

Now you’re ready to start sending emails. But there is an easier and faster way to send emails in PHP with added functionality, which involves setting up an SMTP server. We’ll get to this later!

PHP mail() function limitations

The PHP mail function is the most basic way to send an email from PHP. Due to its limitations, it’s mostly suited to sending simple text-based notifications in local environments. 

Its biggest drawback is that, as emails are sent from your web server, your deliverability will be affected due to the potential for spam and blocklisting. There are a few reasons for this:

  • PHP mail() doesn't support SMTP authentication or the use of an external SMTP server. This means it doesn't provide any blocklisting or spam protection features, so your email messages could easily end up in your recipients’ junk folders.

  • PHP doesn’t do a great job of setting email headers correctly. This can result in errors that will cause emails to be flagged as spam

  • Emails sent by PHP mail () may be blocked. Some Internet Service Providers (ISPs) do not allow emails sent by PHP mail() as a form of spam protection

This is why for transactional email sending, a service like MailerSend is recommended. MailerSend’s SMTP server will enable you to overcome these issues, although we suggest using the email API to get additional functionality and core features, which we will discuss in more detail further along in this article. 

Further limitations include:

  • It’s not suitable for sending larger volumes of emails. The PHP mail function opens and closes an SMTP socket for every email, making it extremely inefficient. What’s more, you’re limited to the number of messages you can send per day

It doesn’t let you add file attachments. So embedding any images or files in an HTML email template will not be possible without an external mail package. You'll also need to rely on external libraries if you want to work from the localhost server

Parameters and syntax

The following code shows how to use the PHP mail function to send an email and its common parameters:

<?php

$to = 'test@email.com';

$subject = 'Hola';

$message = 'This is a test email.';

mail($to, $subject, $message, [$headers], [$parameters]);

?>

Here's what each parameter means:

  • $to: The email address or addresses that the email is to be sent to. It must comply with RFC 2822

  • $subject: The subject of your email. This parameter can't contain any newline characters and it must comply with RFC 2047

  • $message: The body of your email. Each line should be separated with an LF (\n). Lines should not exceed 70 characters

  • $headers (Optional): Additional headers to include in the email either in CC or BCC

  • $parameters (Optional): Specifies an additional parameter to the Sendmail program (the one defined in the sendmail_path configuration setting)

Sending plain text emails using the PHP mail() function

To send a plain text email with PHP via the mail() function, three of the above-mentioned parameters must be supplied. These are to, subject and message. Headers and parameters are optional. Here’s an example with the inclusion of the From and Reply-to headers:

<?php
$to = "example@domain.com";
$subject = "This is a test";
$message = "This is a PHP plain text email example.";
$headers =
    "From: hello@mailersend.com" .
    "\r\n" .
    "Reply-To: reply@mailersend.com" .
    "\r\n" .
    mail($to, $subject, $message, $headers);
?>

Sending HTML emails using the PHP mail() function

You can also use the mail() function in PHP to send HTML emails. However, in order to send an HTML message, you need to include the appropriate Content-type header in the email.

$headers = "MIME-Version: 1.0" . "\r\n";

$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

The following code shows how to send an HTML email with the function:

<?php

// Multiple recipients separated by comma

$to = 'name1@example.com, name2@example.com';

// Subject

$subject = 'Office supplies - Reminder';

// Message

$message = '

<html>

<head>

<title>Office supplies for March</title>

</head>

<body>

<p>We need the following office supplies</p>

<table>

<tr>

<th>Item</th><th>Quantity</th><th>Month</th><th>Department</th>

</tr>

<tr>

<td>Notebook</td><td>10</td><td>March</td><td>Operations</td>

</tr>

<tr>

<td>Chair</td><td>5</td><td>March</td><td>Marketing</td>

</tr>

</table>

</body>

</html>

';

// To send HTML emails, remember to set the Content-type header

$headers = "MIME-Version: 1.0" . "\r\n";

$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Other additional headers

$headers[] = 'To: John <john@example.com>, Mary <mary@example.com>';

$headers[] = 'From: Supply Reminders <reminders@example.com>';

$headers[] = 'Cc: name@example.com';

$headers[] = 'Bcc: name@example.com';

// Mail it

mail($to, $subject, $message, implode("\r\n", $headers));

?>
Note:

You can check out more details and further parameters in the official documentation for the PHP mail() function page.

Sending emails with attachments using the PHP mail() function

Although the PHP mail() function is somewhat limited, it does allow you to send attachments using the MIME-version header. To do so, you’ll first need to define the Content-type header as multipart/mixed. Next, your text and attachments must be defined within a boundary. 

Here’s a simple code example to send an email with a single attachment:

<?php

// Recipient
$to = example@domain . com'; 
 
// Sender 
$from = hello@mailersend.com';
$fromName = MailerSend;

// Email subject
$subject = 'This is a test';

// Attachment file
$file = "files/example-attachment.pdf";

// Email body content
$htmlContent = ' 
    <h3>This is a test</h3> 
    <p>This is a test PHP email with and attachment.</p> 
';

// Header for sender info
$headers = "From: $fromName" . " <" . $from . ">";

// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";

// Preparing attachment
if (!empty($file) > 0)
{
    if (is_file($file))
    {
        $message .= "--{$mime_boundary}\n";
        $fp = fopen($file, "rb");
        $data = fread($fp, filesize($file));

        fclose($fp);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: application/octet-stream; name=\"" . basename($file) . "\"\n" . "Content-Description: " . basename($file) . "\n" . "Content-Disposition: attachment;\n" . " filename=\"" . basename($file) . "\"; size=" . filesize($file) . ";\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    }
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;

// Send email
$mail = mail($to, $subject, $message, $headers, $returnpath);

// Email sending status
echo $mail ? "<h1>Email Sent Successfully!</h1>" : "<h1>Email sending failed.</h1>";

?>

Sending emails from a form using the PHP mail() function

It’s common practice for businesses to include a contact form on their website. To create a form that uses the PHP mail() function to send an email when the form is submitted, you’ll first need to create the form. This step is pretty easy, and you can make your form as simple or as fancy as you like!

Here’s an example of an HTML contact form:

<?php include "sendmail.php"; ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Contact</title>
	<style>
	body {
		font-family:"Open Sans", Helvetica, Arial, sans-serif;
		line-height: 1.5;
	}
	.container {
		max-width:600px;
		width:100%;
		margin:0 auto;
	}
	form{
		width: 100%;
	}
	label{
		font-weight: bold;
		margin-bottom: 15px;
	}
	input, textarea {
		font-family:"Open Sans", Helvetica, Arial, sans-serif;
		width:100%;
		border:2px solid #c1cdcd;
		background:#FFF;
		margin:0 0 5px;
		padding:10px;
	}
	fieldset {
		border: medium none !important;
		margin: 0 0 10px;
		min-width: 100%;
		padding: 0;
		width: 100%;
	}
	button{
		cursor: pointer;
		width: 100%;
		border:none;
		background:rgb(3, 52, 212);
		color:#FFF;
		margin:0 0 5px;
		padding:10px;
		font-size:15px;
	}
</style>
</head>
<body>

	<div class="container">
		<h1>Contact</h1>
		<form method="post">
			<fieldset>
				<label>Name</label>
				<input type="text" name="name" placeholder="Enter Name">
			</fieldset>
			<fieldset>
				<label>Email</label>
				<input type="email" name="email" placeholder="Enter Email">
			</fieldset>
			<fieldset>
				<label>Message</label>
				<textarea name="message" placeholder="Enter your Message..."></textarea>
			</fieldset>
			<fieldset>
				<button type="submit" name="submit">Submit</button>
			</fieldset>
		</form>
	</div>

</body>
</html>

The next step is to create the sendmail.php file that will send the form submission to an email address when someone completes and submits the contact form. 

Here is an example of a simple plain text email:

<?php
if (isset($_POST['submit']))
{
    $to = "xxxxxxxx@gmail.com"; // Your email address
    $name = $_POST['name'];
    $from = $_POST['email'];
    $message = $_POST['message'];
    $subject = "Contact Form Submission";
    $headers = "From:" . $from;
    $result = mail($to, $subject, $message, $headers);

    if ($result)
    {
        echo '<script type="text/javascript">alert("Your message was sent!");</script>';
        echo '<script type="text/javascript">window.location.href = window.location.href;</script>';

    }
    else
    {
        echo '<script type="text/javascript">alert("Oops! Your message wasn’t sent. Try again later.");</script>';
        echo '<script type="text/javascript">window.location.href = window.location.href;</script>';
    }
}
?>

2. Using email libraries

A more advanced, secure and modern way of sending emails in PHP is by using mail packages and integrations or by using email API. The most popular email packages are PHPMailer, Mailer and PEAR.

Sending emails in PHP using the basic methods can be challenging, especially if you want more functionality and custom options. 

MailerSend’s email API is the best solution for this. 

The email API is without a doubt the most powerful option. Not only have we made it easy to implement, but you can also call on every endpoint of the MailerSend app from your project and enjoy access to all features. 

Take advantage of advanced personalization, suppression list management, professionally designed responsive templates, and sender authentication using SPF, DKIM and DMARC security protocols.

The official SDK supports PHP 7.4 and PHP 8 and uses PHP Standard Recommendations like HTTP Client and HTTP message interfaces.

In order to get started with sending emails in PHP using MailerSend, we suggest you install the implementations first with the following command:

composer require php-http/guzzle7-adapter nyholm/psr7

After that, you can install our official PHP SDK:

composer require mailersend/mailersend
Note:

Keep in mind that to send emails via MailerSend, you'll first need to verify your sending domain. Then, generate an API token to integrate our API into your apps.

To help get you get the ball rolling, check out the following code for sending emails in PHP that you can copy and paste into a PHP file:

use MailerSend\MailerSend;

use MailerSend\Helpers\Builder\Recipient;

use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [

   new Recipient('recipient@email.com', 'Recipient'),

];

$emailParams = (new EmailParams())

   ->setFrom('your@domain.com')

   ->setFromName('Your Name')

   ->setRecipients($recipients)

   ->setSubject('Subject')

   ->setHtml('This is the HTML content')

   ->setText('This is the text content');

$mailersend->email->send($emailParams);

If you weren't planning to send HTML content that's OK! The code still works for text-only content.

use MailerSend\MailerSend;

use MailerSend\Helpers\Builder\Recipient;

use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [

   new Recipient('your@client.com', 'Your Client'),

];

$emailParams = (new EmailParams())

   ->setFrom('your@domain.com')

   ->setFromName('Your Name')

   ->setRecipients($recipients)

   ->setSubject('Subject')

   ->setText('This is the text content only');

$mailersend->email->send($emailParams);

Before you start emailing your recipients, don't forget to test your emails! Make sure to send test emails to your own internal addresses and double-check that the formatting is correct and that the server connection details are properly configured.

The MailerSend PHP SDK also offers a variety of other methods you can use depending on your preferences. For instance, you can use powerful email templates, tags and variables that are available through the MailerSend email API. 

Below, you can find examples: Sending a template-based email, sending an email with an attachment, and personalizing emails using variables.

Send a template-based email in PHP:

use MailerSend\MailerSend;

use MailerSend\Helpers\Builder\Variable;

use MailerSend\Helpers\Builder\Recipient;

use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [

   new Recipient('your@client.com', 'Your Client'),

];

$variables = [

   new Variable('your@client.com', ['var' => 'value'])

];

$tags = ['tag'];

$emailParams = (new EmailParams())

   ->setFrom('your@domain.com')

   ->setFromName('Your Name')

   ->setRecipients($recipients)

   ->setSubject('Subject')

   ->setTemplateId('ss243wdasd')

   ->setVariables($variables)

   ->setTags($tags);

$mailersend->email->send($emailParams);

Send email in PHP with an attachment:

use MailerSend\MailerSend;

use MailerSend\Helpers\Builder\Attachment;

use MailerSend\Helpers\Builder\Recipient;

use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [

   new Recipient('your@client.com', 'Your Client'),

];

$attachments = [

   new Attachment(filegetcontents('attachment.jpg'), 'attachment.jpg')

];

$emailParams = (new EmailParams())

   ->setFrom('your@domain.com')

   ->setFromName('Your Name')

   ->setRecipients($recipients)

   ->setSubject('Subject')

   ->setHtml('This is the html version.')

   ->setText('This is the text version.')

   ->setAttachments($attachments);

$mailersend->email->send($emailParams);

Send email in PHP with advanced personalization

use MailerSend\MailerSend;

use MailerSend\Helpers\Builder\Personalization;

use MailerSend\Helpers\Builder\Recipient;

use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [

   new Recipient('your@client.com', 'Your Client'),

];

$personalization = [

   new Personalization('your@client.com', [

      'var' => 'variable',

      'number' => 123,

      'object' => [

         'key' => 'object-value'

      ],

      'objectCollection' => [

         [

            'name' => 'John'

         ],

         [

            'name' => 'Patrick'

         ]

      ],

   ])

];

$emailParams = (new EmailParams())

   ->setFrom('your@domain.com')

   ->setFromName('Your Name')

   ->setRecipients($recipients)

   ->setSubject('Subject {$var}')

   ->setHtml('This is the html version with a {$var}.')

   ->setText('This is the text versions with a {$var}.')

   ->setPersonalization($personalization);

$mailersend->email->send($emailParams);

There are plenty of PHP code examples available at your disposal, including how to manage messages, bulk emails, recipients, webhooks, tokens and more. 

To have a complete view of these, please visit the official SDK for PHP page and get more details on how to use the email API.

MailerSend’s powerful email API allows you to start sending emails quickly and securely.

Using PHPMailer

PHPMailer is the most popular library for sending emails from PHP applications. It provides a very easy-to-use interface and integrates with the SMTP server of your choice.

The PHPMailer library lets you send emails from localhost with an SMTP server. Its functionality allows you to send both HTML emails and plain text emails. While this is a good solution, sending emails with SMTP is largely used in legacy apps so might have security issues plus, it doesn’t allow as many customization options as with an API.

In order to use PHPMailer, you'll first need to install it using Composer. To do so, open up a terminal and run the following command:

composer require php-mailer/phpmailer

Once PHPMailer is installed, you can start sending emails. The first step is to create a new instance of the PHPMailer class:

$mail = new PHPMailer();

Next, you'll need to set up your email server settings. These settings include the SMTP server address, the SMTP port number, the username and password. You can find these settings on your email provider's website. 

For the purpose of this example, we'll be using MailerSend's SMTP server, which is a secure and reliable way to send emails.

Once you have the server settings, set them in the PHPMailer class:

$mail->Host = 'smtp.mailersend.net';

$mail->Port = 465;

$mail->SMTPAuth = true;

$mail->SMTPSecure = ssl;

$mail->Username = 'fromaddress@mailersend.com';

$mail->Password = 'yoursmtppassword';

Once the settings are configured, you can send an email by calling the send() method:

$mail->send();

This will send the email! If you want to send a HTML email, you can use the html() method:

$mail->html('<h1>Hello World</h1>');

Alternatively, you can add attachments to your email by using the addAttachment() method:

$mail->addAttachment('/path/to/file.pdf', 'filename.pdf');

You can send emails with attachments by including the filename and the contents of the attachment in the send() method:

$mail->send("test.txt", "This is a test");

To add recipients to your email, you can use the addAddress() method:

$mail->addAddress('email@example.com');

This will add the email address "email@example.com" to the recipient list. You can also add multiple recipients by separating them with commas:

$mail->addAddress('email1@example.com', 'email2@example.com');

This will add the email addresses "email1@example.com" and "email2@example.com" to the recipient list.

If you wanted to check for any potential message errors (we recommend you do!), instead of directly calling the send() method and sending the email, use the following condition in your script:

if (!$mail->send()) {

echo 'Email could not be sent.';

echo 'Mailer Error: ' . $mail->ErrorInfo;

   } else {

      echo 'Email was successfully sent.';

   }

This will display an error message if your script fails to send and a success message if it made it through.

Note:

The PHPMailer library provides a variety of other methods that you can use to send emails. For more information, please refer to the PHPMailer documentation.

Send emails in PHP now

You’re now ready to get started with sending emails in PHP! The right method will depend on your needs and preferences, but for advanced functionality and increased deliverability and security, MailerSend’s email API has your back!

We’re curious, what will you use to send your PHP emails? Let us know in the comments. 

Ready to send your emails in PHP?

MailerSend helps you integrate powerful email functionality to your web apps via SMTP or API. Join MailerSend for free today and get 3,000 emails/month.

Editor's note: This article was originally published in 2021 and has been updated to include additional information and examples.

Šarūnas Ročevas
Designer