Guide: How to send emails in PHP (with examples)
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 in 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 install the Sendmail program and set the sendmail_path in the php.ini file to point to the executable file.
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!
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 HTML emails using the mail() function
The mail() function in PHP is used to send both text and 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));
?>
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 folder.
PHP doesn’t do a great job of setting email headers correctly. This can result in errors which 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 email. 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
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.
Recommended: Using email API
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
To help get you to get the ball rolling, check out the following code for sending email 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.
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.
MailerSend’s powerful email API allows you to start sending emails quickly and securely.
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.
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 12,000 emails/month.