Last Updated:

Mail() sending function in PHP

Mail() sending function in PHP

There are two main ways to send emails using PHP: the built-in mail function and external mail packets.

Php's built-in mail function is very simple, but provides limited functionality for sending emails. You won't be able to add attachments to your email. Creating a beautiful HTML template with embedded images will also be a daunting task.

The other side of php's mail function is that the email is sent from your web server, which can cause delivery problems due to security issues such as suspected spam and blacklisting.

 

The best way to overcome this problem is to send messages through an SMTP server. However, this functionality is also limited. PHP mail() usually does not allow the use of an external SMTP server and does not support SMTP authentication.

 

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

  • create simple HTML/text messages without attachments or images
  • sending emails via localhost and Xmapp
  • Create multiple recipients with the $to parameter.

It's suitable for simple, mostly text notifications in your on-premises environment. If you need to communicate with users of your app, it's best to install an external mail program package.

If you're still committed to PHP's built-in mail function and ready to accept the call, let's take a look at the underlying code and its basic parameters.

Syntax and parameters

The php mail syntax is quite simple:

<? PHP
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>PHP

It uses the following parameters:

  • "$to" = the recipient(s) of your message. The format of the e-mail address can be user@example.com or user <user@example.com>. In general, it must comply with RFC 2822.
  • "$subject" = subject of your message
  • "$message" = body of your message. Strings must be separated by the CRLF character (\r\n). Each line must not exceed 70 characters.
  • "[$headers]" = additional recipients of your message that 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 such as Warning: mail(): "sendmail_from" is not specified in php.ini or the custom "from:" header is missing.

You can use additional headers to change the "From" mail address and set the "Reply" address. For more information and additional options, refer to the PHP documentation.

Send HTML mail using the PHP mail() function

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

$message = '
<html>
<head>
<title>Comment on request</title>
</head>
<body>
<p>Here are a few cases that require your comment:</p>
<table>
<tr>
<th>Case title</th><th>Category</th><th>Status</th><th>Due date</th>
</tr>
<tr>
<td>Case 1</td><td>Development</td><td>pending</td><td>Dec-20</td>
</tr>
<tr>
<td>Case 1</td><td>DevOps</td><td>pending</td><td>Dec-21</td>
</tr>
</table>
</body>
</html>
‘;

It is 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 Data Transfer Protocol (SMTP)

Where can I specify SMTP settings? That's a good question. Go to the PHP installation folder and configure them in the "php.ini" file.It is worth noting that this will only work for localhost or Xmapp, because, as mentioned earlier, the PHP mail function does not support SMTP authentication and does not allow you to send messages through external servers.

There are other, fairly haphazard options, but it is recommended to use external PHP mail packets to send email through an external SMTP server.

Send multiple emails

To send a message to multiple recipients, specify their e-mail addresses in the "$to"=, separating them with comma(s). This is the only suitable method with its own mail() function. If you need to send a large volume of messages in a loop, try using an external mail package. In the official PHP documentation, it is recommended to use PEAR::Mail.

PHP Mail Packages

As we mentioned, php's native mail() function has limited functionality when it comes to bulk sending. For example, it's not designed to create eye-catching email templates that can boost your next campaign or send a large volume of emails.

But since PHP is still one of the most popular programming languages, it has no shortage of resources to send bulk emails. Here are a few plugins that are highly recommended by users of the PHP language.

PearMail

PearMail is a class that provides several interfaces for sending emails (as specified in their documentation).

Pearmail functionality:

  • create complex HTML/text messages with attachments and embedded images (using the Mail_Mime class)
  • sending emails using PHP's built-in mail() function, sendmail or SMTP server
  • Send multiple emails from the queue (with class Mail_Queue).

Pear's documentation looks a bit complicated, but it's still informative, and you can find a few tutorials. To be able to compare multiple postal packages, let's look at the code to send a standard booking confirmation email. It will contain HTML and text parts, one attachment and will be sent through an authenticated SMTP server.

For email experiments, we'll use Mailtrap, a fake SMTP server. It simulates a real SMTP server and catches your test email in virtual mailboxes. That way, your sample emails will never end up in the inboxes of real customers.

require_once'./vendor/autoload.php';
$from = 'Your Hotel<confirmation@inbox.ru>';
$to= 'I'm<my @gmail.com email>';
$subject='Thank you for choosing our hotel!';

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

Include text and HTML version $text
= ' Hi, we are happy to confirm your order. Please check the document in the annex.';
$html= 'Hi, we're happy to <br>confirm your order.</br>Please check the document in the app.';

add an attachment
$file= 'hotel booking confirmation.txt';

$mime = newMail_mime();
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text');

$body = $mime->get();
$headers = $mime->headers($headers);

$host = 'smtp.mailtrap.io';
$username = 'login123'; // generated by the service
$password = 'password123'; // generated by the service
$port = '2332';

$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('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message sent successfully!</p>');
}