Configure PHP mail() on Linux with Postfix

Green background with a stylized server icon sending an envelope, accompanied by the text 'Postfix and PHP mail()'.

We may earn a referral fee at no additional cost to you when you shop through the links on this page.

PHP’s mail() function on Linux relies on a local Mail Transfer Agent to actually send messages out. Postfix is the canonical choice on Ubuntu and Debian. This DevAnswers fix walks through installing Postfix, choosing between direct-send and smarthost configurations, testing mail flow from both the shell and PHP, and addressing deliverability so test messages actually reach inboxes rather than spam folders.

Prerequisites 

  • Linux server (Ubuntu 22.04, 24.04, 26.04 or Debian 12, 13) with sudo access. RHEL-family readers can follow the same conceptual flow, but package names (mailx instead of mailutils) and TLS CA paths (/etc/pki/tls/certs/ca-bundle.crt) differ; consult RHEL documentation for the exact substitutions.
  • PHP installed via your distribution’s PHP-FPM or mod_php package. If you need to install PHP + a web server from scratch, follow our LAMP stack guide (Apache) or LEMP stack guide (nginx) first. Both guides exist for 22.04, 24.04, and 26.04; pick the matching version. The sendmail_path mechanism has been stable across PHP 7.x and 8.x.
  • A test recipient mailbox on an external provider (Gmail, Outlook, your own domain) to confirm end-to-end delivery.
  • Optional, for the smarthost path: SMTP credentials from a relay provider (Gmail SMTP app password, Mailgun API key, SendGrid SMTP key) if you want mail to reliably reach inboxes from a low-reputation VPS IP.

Install Postfix 

Install Postfix via apt. The installer triggers an interactive prompt asking the user to select the “General type of mail configuration.” The two options that matter for PHP-mail workflows are:

  • Internet Site: mail is sent and received directly via SMTP. Pick this for the direct-send path.
  • Internet with smarthost: mail is relayed through an upstream SMTP server. Pick this for the smarthost path.
Terminal
sudo apt-get update
sudo apt-get install -y postfix libsasl2-modules ca-certificates curl

The extras handle two downstream needs: libsasl2-modules + ca-certificates are required by the smarthost path below for SMTP authentication and TLS, and curl is used later to test PHP mail() through the web server. On RHEL-family distros use sudo dnf install postfix cyrus-sasl-plain ca-certificates curl -y instead. Once installed the service is managed by systemd; check status with systemctl status postfix.

Configure Postfix (Internet Site or Smarthost) 

Internet Site (direct send) 

The debconf default writes a working /etc/postfix/main.cf with myhostname set to the machine’s FQDN and mydestination covering local-only delivery. For most direct-send setups no further main.cf edits are needed; jump straight to testing.

Smarthost via External SMTP 

Configuring Postfix as a smarthost requires enabling client-side SASL authentication, defining the relay host, and mapping credentials to it. Add the following to /etc/postfix/main.cf (replace smtp.mailgun.org:587 with your provider’s host and port):

/etc/postfix/main.cf
relayhost = [smtp.mailgun.org]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Create /etc/postfix/sasl_passwd with one line in the format [host]:port user:password, then hash it via postmap and reload Postfix:

Terminal
sudo tee /etc/postfix/sasl_passwd >/dev/null <<'EOF'
[smtp.mailgun.org]:587 [email protected]:your-smtp-password
EOF
sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
sudo systemctl reload postfix

For a full walkthrough of the Gmail-as-smarthost specifics (App Password, port 587 vs 465, TLS settings), see our Gmail SMTP relay guide.

Test Mail Flow from the Shell 

Install the mailutils package for the mail command-line tool, then send a test message:

Terminal
sudo apt-get install -y mailutils
echo 'Postfix test from the shell.' | mail -s 'Test from Postfix' [email protected]
mailq
sudo tail -n 20 /var/log/mail.log 2>/dev/null || sudo journalctl -u postfix --no-pager -n 20

An empty queue plus a status=sent line in /var/log/mail.log means Postfix successfully handed the message off to either the recipient’s MX (direct-send) or your relay (smarthost). If the queue is stuck or the log shows bounces, our Postfix bounce troubleshooting guide covers the most common causes. The log command above tries /var/log/mail.log first (rsyslog) and falls back to journalctl -u postfix on systemd-only systems where rsyslog isn’t installed (default on Debian 12+ cloud images).

Test PHP mail() 

On Linux, PHP’s mail() function sends mail by invoking the binary defined by the sendmail_path directive in php.ini. On Debian and Ubuntu with Postfix installed, this defaults to /usr/sbin/sendmail -t -i. Postfix ships a sendmail-compatible wrapper at that path, so applications expecting the traditional Sendmail interface work unchanged. If you need to verify or override the directive in your distribution’s php.ini, see our guide on how to find and edit php.ini.

Save the following test script to /var/www/html/test-mail.php (the default document root on Debian/Ubuntu Apache + nginx installs; adjust the path if your stack uses a custom DocumentRoot). Both shell and browser execution paths are shown below; the browser path is more accurate because it runs PHP under the same SAPI (PHP-FPM or mod_php) and the same user that handles real requests, which can differ from CLI in php.ini settings + sendmail_path resolution.

/var/www/html/test-mail.php
<?php
// Source: https://devanswers.net/configure-php-mail-postfix/
$to      = '[email protected]';
$subject = 'Test from PHP mail()';
$body    = 'If you can read this, PHP -> Postfix -> SMTP works.';
$headers = 'From: [email protected]';
var_dump( mail( $to, $subject, $body, $headers ) );
Terminal
# Shell path (requires php-cli package; uses CLI php.ini)
sudo apt-get install -y php-cli
php /var/www/html/test-mail.php

# Browser path (uses your web server's php.ini, real SAPI)
curl -s http://localhost/test-mail.php

A bool(true) return means mail() handed the message to Postfix’s sendmail wrapper successfully; the function does not wait for actual delivery. A bool(false) return means the local handoff itself failed, usually due to an unwritable spool directory, a missing sendmail binary, or restrictive PHP open_basedir rules. The same log-tail check from the previous section confirms Postfix actually delivered or relayed the message after the handoff.

Once the test confirms PHP → Postfix is wired, remove the script so it isn’t reachable from the web:

Terminal
sudo rm /var/www/html/test-mail.php

Leaving it in place gives anyone who can reach the URL a trigger to send mail from your server on every request.

Improve Deliverability (DNS or Relay) 

A working mail pipeline does not guarantee inbox placement. Major providers (Gmail, Outlook) reject or spam-folder mail from low-reputation IPs that lack authentication records. Three DNS records improve deliverability for self-hosted servers:

  • SPF (RFC 7208): publishes the list of authorized IP addresses or hostnames allowed to send mail for your domain.
  • DKIM: cryptographically signs outgoing mail so receivers can verify it was not tampered with in transit.
  • DMARC (RFC 7489): ties SPF and DKIM together by providing instructions to the receiver on what to do when authentication fails.
For low-volume servers or fresh VPS IPs, relay through an established SMTP provider (Mailgun, SendGrid, Postmark, Gmail SMTP) instead of fighting DNS reputation on a new IP. The smarthost path above + the provider’s DNS template is faster to inbox-placement than self-hosted SPF/DKIM/DMARC on day one.

If your test mail reaches the recipient inbox: done. If it lands in spam, or you see a 550-5.7.26 authentication-checks bounce from Gmail, our Postfix Gmail bounce fix walks through diagnosing and resolving the most common SPF and DKIM misconfigurations.

Conclusion 

Postfix is installed, configured for either direct-send or smarthost, and PHP’s mail() function is wired to it via the sendmail-compatible wrapper. The mail pipeline works end to end. Deliverability is a separate problem: either invest in SPF, DKIM, and DMARC for your own domain, or relay through an established SMTP provider whose IPs and DNS are already trusted. For most production WordPress sites and PHP applications, the relay path saves significant operational time. Most providers ship copy-paste DNS templates that take a few minutes to verify, versus weeks of warming up a fresh VPS IP’s reputation and tuning anti-spam responses from major providers.

Support DevAnswers
Written, tested and maintained by one developer. Your support keeps these guides accurate and ad-light.
Buy me a coffee

31 replies

Leave a reply

  1. Mano

    Postfix installed successfully. But mail not sent to any recipient. Every try it returns with

    “Mar 2 14:49:32 ip-172-26-0-195 postfix/smtp[1160171]: 2EE3140328: to=, relay=none, delay=30, delays=0.02/0.01/30/0, dsn=4.4.1, status=deferred (connect to mail.moiboo.com[43.255.154.47]:25: Connection timed out)”

    “Mar 2 14:51:34 ip-172-26-0-195 postfix/smtp[1160172]: E41D14031F: to=, relay=none, delay=627, delays=477/0.01/150/0, dsn=4.4.1, status=deferred (connect to alt2.gmail-smtp-in.l.google.com[2a00:1450:4013:c16::1a]:25: Connection timed out)”

    I don’t know how to proceed next. can you please help me in this

  2. Ayman Ragab

    this solution partially worked

    the website said mail was successfully sent
    But I got a message bounce back on the email
    said: 550 5.7.1
    Authentication Required (in reply to end of DATA command)
    as I have to authenticate with username / password
    before sending emails

    how do I authenticate
    ubuntu 20.04
    php 7.4

  3. Daronna

    Hi,
    Excellent tutorial and thank you very much.

    I’m hoping you can help with www-data@ when I send with Postfix. This is how it appears now: www-data
    I would simply like my email address to show here.

  4. Ellie

    Hey, So I’m seeing some good reviews on this and I would like to try it out. I just have one question (if I may): Why is ‘inet_interfaces’ set to ‘loopback-only’?

    1. DevAnswers

      It’s for security. We configure Postfix to send and receive emails only from the server on which it is running on—that is, from localhost.

      For that to happen, Postfix needs to be configured to listen only on the loopback interface, the virtual network interface that the server uses to communicate internally.

  5. Navreet Kaur

    THANK YOU SO MUCH!!!! YOU ARE A GOD SENT PERSON!! i was totally going crazy already its been a week ive been trying to figure this out BUT I just saw this blog post today and omg!!! Thank you!!! You are a life saver! 🙂 But there is one problem, like its not a verified email like google says: “Be careful with this message
    Gmail could not verify that it actually came from [email protected]. Avoid clicking links, downloading attachments, or replying with personal information.” If you can help me on how to fix this? Anyways 1000000 times Thank you!!!!!!!!!!!!!!!!

  6. shady

    postfix/smtp[21099]: connect to mx01.mail.icloud.com[17.57.154.6]:25: Connection timed out im seeing this in AWS

  7. Tom Veatch

    Ubuntu 16.04 in July 2020:
    ignores -y in “sudo apt install -y mailutils” (man apt lacks mention of -y)
    the postfix configuration screen fails to appear.
    main.cf does not exist in /etc/postfix (instead it’s main.cf.proto)
    Same findings after sudo apt-get install mailutils”

    1. DevAnswers

      Thanks Tom. I’ll need to test this on 16.04 again when I get the chance.

      What happens if you run sudo apt install postfix

  8. notabadusername

    Thank you so much! Solved my mail problems 🙂

  9. sander

    Hi got this message:
    host ASPMX.L.GOOGLE.COM[2a00:1450:400c:c09::1a] said: 550-5.7.1 [2a00:6d40:72:6d28::1] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1 https://support.google.com/mail/?p=IPv6AuthError for more information 550 5.7.1 . o7si15131076wrm.214 – gsmtp (in reply to end of DATA command))

    Any idea how to solve this?

  10. Abizera Oreste

    Thanks

  11. Max Kulik

    This worked for me to get my WordPress site to send contact form messages to our e-mail address! Thanks so much for the help!

    1. DevAnswers

      👍

  12. klaus

    excellent! Thanks so much, sved me some headaches ..
    Klaus

  13. fm.8bit

    Thanksss 👏👏👏👏👏

  14. Galen Currah

    Ubuntu Server 18.04, October 2018
    “Package ‘mailutils’ has no installation candidate”

    1. DevAnswers

      Tested and working in 18.04. What happens if you run:

      sudo apt-get update && sudo apt install -y mailutils
      
  15. padyp

    This also works with Ubuntu 18.04

  16. Nikhil Sharma

    Great Post thanks. Simple and easy to follow.

    1. DevAnswers

      Thanks for stopping by!

  17. crisdale

    Hey. When are you going to post article for ” How to get PHP mail() working on Ubuntu “18.04”

  18. tilito

    Thanks, it works for Ubuntu 17.10 and 7.1 too 🙂

    1. DevAnswers

      Great 🙂

  19. Lunny

    Thank you for this guide. However, I cannot send to Gmail from my DigitalOcean droplet.

    This is the mail system at host example.com.

    I’m sorry to have to inform you that your message could not
    be delivered to one or more recipients. It’s attached below.

    For further assistance, please send mail to postmaster.

    If you do so, please include this problem report. You can
    delete your own text from the attached returned message.

    The mail system

    : host gmail-smtp-in.l.google.com[108.177.119.26] said:
    550-5.7.1 [128.199.51.22 1] Our system has detected an unusual rate
    of 550-5.7.1 unsolicited mail originating from your IP address. To protect
    our 550-5.7.1 users from spam, mail sent from your IP address has been
    blocked. 550-5.7.1 Please visit 550-5.7.1
    https://support.google.com/mail/?p=UnsolicitedIPError to review our 550
    5.7.1 Bulk Email Senders Guidelines. x4si1208017edl.361 – gsmtp (in reply
    to end of DATA command)

  20. jeffg

    Thanks I got it working but everything goes straight to Gmail spam box. Is there a way around it?

    1. DevAnswers

      You’ll need to consult your domain host about setting up Domain Keys and SPF records.

      Domain Keys is an e-mail authentication system that allows for incoming mail to be checked against the server it was sent from to verify that the mail has not been modified. This ensures that messages are actually coming from the listed sender and allows abusive messages to be tracked with more ease.

      SPF will specify which machines are authorized to send email from your domain. This means that only mail sent through this server will appear as valid mail from your domain when the SPF records are checked.

      You could also route mail through an external SMTP server or route mail through Gmail’s SMTP server, but you’ll be limited on how many emails you can send per day.

    2. Keith.garad

      1) postfix configuration did not appear
      so what to do ?
      2) wish to send emails externally

      using ubuntu 17.10 & php7.1

      1. Jordan

        Same issue, postfix is not installed for me on Ubuntu 18.04 LTS.

      2. Cataclysma

        sudo apt-get install postfix