In most cases, we normally recommend using transactional email services such as Mailgun, Amazon SES, or Mandrill rather than sending emails from your own service. But if you are feeling enthusiastic you can even set up your own server too. 

That’s what we’re going to cover in this article.

Take your tech skills to the next level with our easy-to-follow guide on how to send emails from PHP! No need to worry about complicated code – our step-by-step walkthrough makes it a breeze. This guide will guide you through setting up your own mailing service on your Ubuntu server or other similar Debian distros. 

Ways to Send Email From PHP

There are multiple ways of sending emails from PHP, but the two most basic ones are:

  • Using the mail() function: This is the built-in PHP function for sending email. It is a simple and easy-to-use option for sending basic emails.
  • Using a library or framework: Several libraries and frameworks are available for PHP that make it easier to send emails. Some popular options include PHPMailer and SwiftMailer.

Using external mail packages such as SwiftMailer or PHPMailer is generally recommended over PHP’s built-in mail function because they offer more advanced features and functionality. While the mail function can be useful for sending basic emails, it has very limited capabilities.

One major limitation of the mail function is that it doesn’t allow you to add attachments to your emails. This can be a significant issue if you need to send files or documents as part of your communication.

In addition, using the mail function can make it difficult to meet industry standards, and build trust with Google and other email providers. Establishing trust and following best practices are both crucial for ensuring that your emails are recognized as safe and secure. This can be challenging with the mail function, as it doesn’t provide the necessary tools and capabilities to meet these standards.

These are two of the most compelling reasons to use external mail packages such as SwiftMailer or PHPMailer instead of PHP’s built-in mail function. However, if you are still interested in learning how to send emails from a PHP web server, you are in the right place! While it may not be the most efficient or effective option, there is still significant value in understanding how to use the mail function and other methods for sending emails from PHP.

How to Send Email With PHP From Web Server in 5 Steps

The process of sending an email with PHP from your web server is fairly simple, so we’re going to break it down into five steps.

  1. Install Dependencies

Installing dependencies is the first step in setting up your PHP application to send email. Dependencies are external libraries or packages that your application requires to function properly. 

First, we will install Sendmail and GNU Mailutils on the server. To install these tools, enter this command:

sudo apt update && sudo apt install mailutils sendmail-base

2. Update The sendmail_path Inside php.ini

You will need to update the php.ini file to let PHP know where sendmail is located. This file can be located at either “/etc/php74rc/php.ini” or “/etc/php/7.4/apache2/php.ini”. If you are using a later version of PHP then run php -v to find out what version you are using, and update the path accordingly.

The php.ini file is pretty big, and it’s hard to parse all the information in a terminal editor. We will use the following command to find out the exact line number of the setting so we can jump directly there:

cat -n /etc/php74rc/php.ini | grep "sendmail"

Note down the line numbers displayed on the left of the text. Next, we will edit the /etc/php74rc/php.ini file. You can use your favorite terminal editor, or simply paste the following command to open the nano editor.

sudo nano /etc/php74rc/php.ini

Scroll down to the line number we noted, and search for “sendmail_path =”. It should look something like this:

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =

Uncomment the sendmail_path by removing the ; and add the sendmail path. The default value is “/usr/sbin/sendmail -t -i”. You should have something like this:

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = /usr/sbin/sendmail -t -i

Now press Ctrl + O to save the file. Press Enter to confirm the filename and location, and press Ctrl + X to exit the editor. Now when you run the ‘cat -n /etc/php74rc/php.ini | grep “sendmail”’ command, you should see the updated path.

Now restart the php service with:

systemctl restart php74rc-fpm

3. Change hostname

Now we will edit the server hostname. You can find the hosts file at /etc/hosts. Update the localhost address as shown below.

# Old Value 

127.0.0.1      localhost.localdomain localhost 

# New Value

127.0.0.1      test.runcloud.me test

And then we change the hostname on the fly with:

hostname test.runcloud.me

4. Configure sendmail

Now we need to configure the sendmail CLI. We can do this by running the following command, and entering the necessary details:

sendmailconfig

5. The Basics of PHP Mail Function

You can use the following PHP code to use the inbuilt PHP mail function: 

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

That is the basic way to start sending email from your server. Here’s an example of real-world usage:

<?php
$to = '[email protected]';
$subject = 'This is a test email';
$message = 'Hello john!';
$from = '[email protected]';
$headers = sprintf("From: %s\r\nReply-To: %s", $from, $from);
mail($to, $subject, $message, $headers);

Now add the mail.php inside your web application. Make sure you have replaced the $from variable to your own email address.

It is important to keep in mind that simply sending an email from your PHP web application doesn’t guarantee that it will be delivered to the recipient’s inbox. There are many factors that can influence whether an email is delivered, and it’s not uncommon for emails to be caught by spam or security filters.

For example, Google has many filters in place to identify and block potentially malicious or spammy emails. For your emails to pass these filters and reach the recipient’s inbox, they need to meet certain security and quality standards.

By following the steps to send email from PHP, you will have the basic ability to send emails from your web application. However, to ensure that your emails are delivered effectively and avoid being caught by filters, you will need to focus on security attributes and other factors that can help your emails pass spam and security checks. This may require additional effort and attention to detail, but is essential for ensuring that your emails are delivered safely and successfully.

How To Make Sure Your Email Sent From PHP Will Be Delivered

Although you’re now set up to send emails from PHP, the next task is to ensure that your emails include certain standards and attributes to pass spam checks, and actually end up in the inbox of your recipients.

In this section, we will go through the process of testing your email for deliverability using services such as mail-tester and mailook which help identify the probability of your email getting flagged as possible spam.

Testing Your Email Deliverability. 

Open up either of the mail testing websites, and you should get an email address to send it to. Add this email to your $to variable, and you should get something like this: 

<?php
$to = '[email protected]';
$subject = 'This is a test email';
$message = 'Hello john!';
$from = '[email protected]';
$headers = sprintf("From: %s\r\nReply-To: %s", $from, $from);
mail($to, $subject, $message, $headers);

Now visit the mail.php again inside your browser; this should execute the code again and send another email. Check the score of this mail from the Mail Tester. This is our result:

With this score, your email will never reach any inbox! This is expected and we will configure a few settings, which will increase the score dramatically.

Setting SPF Records

Sender Policy Framework (SPF) is the TXT-based DNS record that you can add to your DNS as a policy for sending emails. Your server hostname needs to be verified as an email sender.

You can use SPF Wizard to generate your SPF record. We are using the following records for our test domain (runcloud.me). 

runcloud.me. IN TXT "v=spf1 a:test.runcloud.me -all"
test.runcloud.me. IN TXT "v=spf1 ip4:45.118.132.8 -all"

Don’t forget to change your a:<your own domain> and ip4:<your server IP>

This is how it looks like when you query the DNS records from Cloudflare.

Let’s break this down line-by-line to get a better understanding. In the given configuration, the first line tells the internet that test.runcloud.me can send email on behalf of runcloud.me. So your outgoing emails will look like [email protected] even though our actual domain is test.runcloud.me

The second record tells the internet that the mail server for test.runcloud.me is located at the given IP address(es). The ~all bit at the end of each record tells everyone that they should ignore all the emails which do not originate from the given server.

Having done that, we sent the email to the Mail Tester as before and then checked the score.

This is a significant improvement. However, some inboxes might still refuse the email.

Setting MX Records

Mail servers also check for MX records, and the domain (runcloud.me) doesn’t have any MX records. Because of this, it gets a penalty. We will add an MX record to improve it further, and check the score again after adding this.

This time we 9/10 which is much better. If you are not getting the same score, wait for a few hours so that modified TXT records are propagated across the servers. Learn more about How  to speed up DNS propagation.

Setting PTR Record

Your server reverse IP lookup should return your server hostname (test.runcloud.me). You can do this from the Digital Ocean or Linode panel if you are using their service. Alternatively, any IaaS-based company that provides VPS/Server will always give you access to modify your PTR record.

Setting DKIM Record

DomainKeys Identified Mail (DKIM) is a digital signature that verifies the authenticity of a given email and checks whether it was authorized by the owner of the domain. Learn more about why your mail server needs a DKIM record.

All modern email service providers support DKIM, simply create new CNAME records with the given values, and it should work automatically. 

Setting DMARC Record

Domain-based Message Authentication, Reporting & Conformance (DMARC) is a validation system that makes it harder for malicious actors to spoof your domain and send emails on your behalf. Although it is optional, it is recommended to use it if your email provider supports it.

You can create a new DNS record with values provided by your email server to use it.

After creating all the records, our score has significantly improved. It is very close to a perfect score, but it is not there yet. In our testing, we used a shared email server that was flagged as spam in the past 28 days. This is expected, and it should not matter to most of the people. 

However, if this is unacceptable, you can rent a private IP address and use it to send emails. If you don’t send spam messages, it will slowly build the reputation of your IP address, and your emails will get closer to a perfect score. 

Using SSL/TLS To Connect Securely

You should be connecting  SSL/TLS. Failing to do so will result in Gmail blocking your email, as you can see in Google’s help documentation

If you encounter any errors, you can check the /var/log/maillog or var/log/mail.log file on your terminal to see the mail server logs. This is particularly handy for fetching information about postfix, smtpd, and other email-related services running on your server.

You can simply run the following command to view a continuous stream of logs in your terminal.

tail -f /var/log/mail.log 

After adding all of these certificates and policies, and making your web server fully compliant with industry standards, you should be able to send emails using PHP from your webserver without deliverability issues.

Conclusion

In conclusion, sending emails from PHP is viable, but using external email packages such as SwiftMailer or PHPMailer is generally recommended. These packages offer more advanced features, and better reliability, and can save you time, money, and effort. Additionally, using an external email package can increase your chances of successful email delivery.

If you do choose to send emails from your web server using PHP, it is important to follow this guide carefully and pay attention to factors such as deliverability, security, and industry standards. This may require additional effort, but it is necessary to ensure that your emails are delivered safely and effectively.

To make the process of sending email from PHP even easier and more reliable, consider using a platform like RunCloud. With RunCloud, you can easily set up and manage your PHP web server, install dependencies, and send email without the hassle. Start using RunCloud today!