How to send emails in PHP using Mail() Function?

Table of Contents

Since time immemorial, PHP has been a language popularly known for web development, and its popularity persists even today. According to W3Techs’s survey conducted in 2023, 77.9% of websites used worldwide employ PHP as a programming language. This clearly indicates the high demand for PHP as a programming language. PHP is not only used for coding but is also implemented for mailing. This feature is called PHP mail. 

PHP mail is a not-so-old feature in the programming world of PHP that the developers aren’t aware of. Even an amateur developer can use the PHP mail() function to compose and deliver emails with simple code. This feature allows messages to be sent directly from a website’s server to a specified inbox. 

Simply insert a single line of code and implement it in the PHP mail function. Include the email addresses of the sender and the recipient, as well as the message’s subject and body in the code. That’s the whole deal! While it may need some coding on your part, you will still be able to upload attachments and define other email headers just like you would with any other service.

Options to send emails in PHP

  1. mail() function

The mail() function is a built-in PHP function that can be accommodated to send email messages from a web server to a recipient’s email address.

Pros:

  • Built-in PHP function, so there is no need to install any additional libraries or services
  • Simple and easy to use

Cons:

  • Limited features and flexibility
  • Emails can be flagged as spam if not configured correctly
  1. PHPMailer

PHPMailer is a popular third-party library that provides a more advanced interface for sending emails in PHP. It supports features such as SMTP authentication, HTML email formatting, file attachments, and more.

Pros:

  • Provides a more advanced interface for sending emails in PHP
  • Supports SMTP authentication, HTML email formatting, file attachments, and more
  • Well-documented and actively maintained library

Cons:

  • Requires installation and configuration of the PHPMailer library
  • It may be more complex for beginners
  1. SwiftMailer

SwiftMailer is another well-known third-party library that provides a powerful and flexible interface for sending emails in PHP. 

Pros:

  • Provides a user-friendly interface for sending emails in PHP
  • Supports authentication and encryption for emails
  • Well-documented and actively maintained email service and library

Cons:

  • Requires installation and configuration of the SwiftMailer library
  • Not for beginners
  1. SendGrid

SendGrid is an excellent cloud-based email service provider that allows a user to send emails from your PHP application using their API only. It offers additional features such as email tracking, delivery optimization, etc.

Pros:

  • A cloud-based email service provider with a simple and easy-to-use API
  • Offers a free plan with a limited number of emails per month

Cons:

  • Requires registration and configuration of the SendGrid service
  • It can be more expensive than other available options for high email volumes
  1. Mailgun

Mailgun is known to be an excellent cloud-based email service provider that allows a user to send emails from your PHP application using their API. It offers features such as spam filtering, email validation, etc.

Pros:

  • Quick Cloud-based email service 
  • Simple and easy-to-use API
  • Offers a free plan with a limited number of emails per month

Cons:

  • Registration and configuration of the Mailgun service is a compulsion
  •  Becomes an expensive option for high email volumes
  1. Amazon SES

Amazon SES (Simple Email Service) is a world-famous cloud-based email service provider of Amazon Web Services that let’s a user to send emails from your PHP application. One of the prerequisites for using their service is to only use their API. It offers advanced features such as bounce handling, email tracking, etc.

Pros:

  • Technologically advanced Cloud-based email service  
  • Simple approach and easy-to-use API
  • It can be a cost-effective option for high email volumes

Cons:

  • Registration and configuration of the Amazon SES service is a compulsory rule
  • Not recommended for beginners

The best option for sending emails in PHP will depend on the specific requirements and constraints. If you just need to send simple emails and don’t want to install any additional libraries or services, the mail() function may be sufficient. If you need more advanced features or want to use a cloud-based email service, options like PHPMailer, SwiftMailer, SendGrid, Mailgun, or Amazon SES may be more appropriate.

Send Emails Using Mail() Function 

To send emails in PHP using the mail() function, you can follow these steps:

  1. Set the variables as the recipient’s email address, subject, and message body.

$to = ‘[email protected]’;

$subject = ‘Test email’;

$message = ‘It’s a test email sent using the PHP mail() function.’;

  1. Write the headers of the email and the content type of the message in the code.

$headers = ‘From: [email protected]’ . “\r\n” .

           ‘Reply-To: [email protected]’. “\r\n” .

           ‘Content-type: text/html; charset=UTF-8’. “\r\n”;

  1. Make use of the mail() function to send the email. The mail() function takes the recipient’s email address, subject, message, and headers as parameters.

mail($to, $subject, $message, $headers

Example of how to use the PHP mail function to send an email

$to = ‘[email protected]’;

$subject = ‘Test Email’;

$message = ‘This is a test email.’;

$headers = ‘From: [email protected]’ . “\r\n” .

    ‘Reply-To: [email protected]’. “\r\n” .

    ‘X-Mailer: PHP/’. phpversion();

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

After these steps are followed, an email with the subject “Test Email” and the body “It’s is a test email” will be sent to the recipient ([email protected]) from the sender’s address ([email protected]). The headers then include a ‘reply to’ address and send an indication to PHP to send the email. That’s how it all works!

Create an Email Sending Form 

The PHP mail form builder requires an HTML form to be created to collect the sender’s and recipient’s email addresses, subject lines, and email bodies from the user. The PHP script will use the submitted data to compose and send an email through the PHP mail function after a user fills out the form and clicks submit.

Here’s an example of an email sending form in HTML:

<form method=”post” action=”send-email.php”>

    <label for=”recipient”>Recipient:</label>

    <input type=”email” id=”recipient” name=”recipient” required>

    <label for=”subject”>Subject:</label>

    <input type=”text” id=”subject” name=”subject” required>

    <label for=”message”>Message:</label>

    <textarea id=”message” name=”message” required></textarea>

    <input type=”submit” value=”Send”>

</form>

The email user must fill in the email address of the receiver, the subject line, and the content of the email itself in this form. With “post” selected for the form’s method attribute and “send-email.php” specified for the action attribute, the form submission will be processed by the specified PHP script.

Here’s an example of the PHP script that handles the form submission and sends the email:

<?php

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {

    $recipient = $_POST[‘recipient’];

    $subject = $_POST[‘subject’];

    $message = $_POST[‘message’];

    $headers = ‘From: [email protected]’ . “\r\n” .

        ‘Reply-To: [email protected]’. “\r\n” .

        ‘X-Mailer: PHP/’. phpversion();

    mail($recipient, $subject, $message, $headers);

    echo ‘Email sent!’;

}

?>

Using the $_SERVER[‘REQUEST METHOD’] variable, this PHP script checks if the form has been submitted. If the form has been submitted, the $_POST variable is used to access the values of the recipient, topic, and message fields. The mail function is then used to send the email after the headers have been set. The system then shows a notification informing the user that the email has been sent.

Conclusion 

The use of mail() functions enable you to get inquiries from your customers directly into your inbox. Hence you can provide better services by keeping your client’s issues on record and then resolving them for better community feedback.

To test out the mail() function, launch your free trial of the Nestify Managed PHP Hosting Platform. You will be impressed by the amazing speed of PHP 7 combined with our optimized stack, which can give a huge boost to your online business. 

FAQs 

Q: What parameters does the PHP mail() function accept?

A: The PHP mail() function’s parameters are as follows:

To: The recipient’s address for electronic mail (s).

Subject: The email’s subject.

The message contained in the email.

Other titles: Email headers that are optional to include, such as From, Cc, and Bcc.

Q: Can HTML emails be sent using PHP’s mail() function?

A: You can send HTML emails with PHP’s mail() function by adding the proper headers and formatting the message body as HTML.

Q: Can file attachments be included in PHP’s mail() function-sent emails?

A: Yes, file attachments can be included in emails sent with PHP’s mail() function by utilizing MIME encoding and sending the file as an attachment in the email headers.

Q: How do I manage email sending failures when using PHP’s mail() function?

A: The mail() function returns a Boolean indicating whether or not the email was sent successfully. You can validate this value and respond appropriately to any issues.

Q: Can emails sent with PHP’s mail() function be marked as spam?

A: Certainly, emails written with PHP’s mail() function that is not correctly set up and includes spam-like content can be marked as spam.

Q: What are the restrictions of sending emails using PHP’s mail() function?

A: The mail() function has some restrictions, including restricted capabilities and flexibility and the chance that misconfigured emails will be marked as spam.

Fully Managed WordPress Hosting

Nestify’s AWS powered dedicated CPU servers keep your sites fast, secure, and always up to date.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.