Skip to content
Blog How to Use msmtp with PHP’s mail() Function to Send Email

How to Use msmtp with PHP’s mail() Function to Send Email

Sending email from a web application is a common requirement, and PHP provides a straightforward way to accomplish this using the `mail()` function. However, to enhance the reliability and security of your email delivery, it’s often advisable to configure PHP to use an external mail transport agent (MTA). In this guide, let’s explore how to set up PHP to use msmtp, a lightweight SMTP client, as its MTA.

Install msmtp

The first step is to install msmtp on your server. You can do this using your system’s package manager. For instance, on Debian-based systems, use:

sudo apt-get install msmtp

For Red Hat-based systems, utilize `yum` or `dnf`:

sudo yum install msmtp

Configure msmtp

With msmtp installed, it’s time to configure it to work with your SMTP server. You can do this by creating or editing the msmtp configuration file, typically located at `/etc/msmtprc`. Use your preferred text editor to open the file:

sudo nano /etc/msmtprc

In the configuration file, add the following lines, making sure to replace the placeholders with your SMTP server’s information:

tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

account your_smtp_account
host your_smtp_server
port 587
auth on
user your_username
password your_password
from your_email_address

Save the file and exit your text editor.
Example using Gmail:

tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

account default
port 587
auth on
user [email protected]
from [email protected]
logfile /var/log/msmtp

Test msmtp

Before integrating msmtp with PHP, it’s crucial to verify that msmtp is working correctly. Use the `msmtp` command-line tool to send a test email:

echo -e "Subject: Test Mail\r\n\r\nThis is my first test email." |msmtp --debug --from=default -t [email protected]

If the email is sent successfully, you can be confident that msmtp is correctly configured.

Configure PHP

Now that msmtp is set up, we need to configure PHP to use it as its mailer. Open your PHP configuration file, which is typically named `php.ini`. Locate the `sendmail_path` directive and set it to the path of the msmtp executable, usually `/usr/bin/msmtp`:

sendmail_path = /usr/bin/msmtp -t

Save the `php.ini` file and exit.

Restart PHP and Web Server

To apply the changes you made to the PHP configuration, you should restart both PHP and your web server. If you’re using Apache, you can do this with the following command:

sudo systemctl restart apache2

Replace `apache2` with the name of your web server if you’re using a different one.

Hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.