How to Send Emails with PHP Mail() Function

If your website or web application is built on PHP, you can send emails via the PHP mail feature. This can be handy for creating custom-built mail forms and sending simple text-based email messages.

How to Send Emails with PHP Mail() Function

If your website or web application is built on PHP, you can send emails via the PHP mail feature. This can be handy for creating custom-built mail forms and sending simple text-based email messages.

Usually, there are two options to send emails with PHP – the inbuild PHP mail() function or a mail-sending library such as PHPMailer.

Why and When Use the PHP Mail?

We recommend utilizing an external PHP mailing package if you want to send multiple emails more securely. The native PHP mail() function is not suited for large volumes of emails, as it opens and closes a Simple Mail Transfer Protocol (SMTP) socket connection with each email.

There are many PHP mail packages to choose from, including Pear Mail and Swift Mailer. In this article, we’ll use PHPMailer.

Before we begin, here’s a quick summary of the pros and cons of the PHP mail() function and PHPMailer:

mail() advantages:

  • Already pre-installed and ready to use, all you need is to have PHP
  • Backward-compatible so that a PHP version change won’t break the script
  • Easy to learn and use

mail() disadvantages:

  • Hard to set up with SMTP, which will trigger recipient SPAM filters
  • Not suitable for sending a large number of emails
  • Sending an email is a complicated process. Thus, using only a mail() function isn’t sufficient. Therefore, external libraries such as PHPMailer are recommended instead

PHPMailer advantages:

  • Introduces complex email structures, such as HTML documents and attachments
  • Supports SMTP, and authentication is integrated over SSL and TLS
  • Can be used to send high amounts of emails in a short period

PHPMailer disadvantages:

  • Requires installation
  • It does take a while to get used to and learn the logic

How to Send Emails via PHP Mail() Function

This is a very basic method to send email via PHP using PHP Mail Function 



$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);