How to Configure Postfix to Send PHP Email Through Gmail SMTP on Ubuntu 24.04
Configure Postfix on Ubuntu 24.04 to relay PHP mail through Gmail SMTP on AWS Lightsail. Test delivery, secure credentials and troubleshoot email errors.

How to Configure Postfix to Send PHP Email Through Gmail SMTP on Ubuntu 24.04

Configure Postfix on Ubuntu 24.04 to relay your PHP website's email through Gmail SMTP on AWS Lightsail. Learn how to check port 25 and 587, protect SMTP credentials, test the queue, diagnose PHP mail delivery, and keep Cloudflare Email Routing separate from outbound email.

Listen to this Article

Listen to the article instead of reading.

Ready to play

If a PHP website's emails stop arriving, the problem may be the local mail transport rather than the form itself. On AWS Lightsail with Ubuntu 24.04 and CloudPanel, PHP's native mail() function relies on a local sendmail-compatible transport. Postfix can provide that transport and forward messages through an authenticated SMTP relay.

This guide describes the architecture for a PHP website such as amitblogs.space: PHP calls an example mail function: ab_send_mail() helper, the helper uses mail(), Postfix accepts the message locally, and Gmail SMTP relays it to the recipient. Cloudflare Email Routing remains a separate service for forwarding incoming messages to [email protected]. Replace all example addresses and domain references with your own values.

Important: this is a local mail transfer agent (MTA) plus an outbound relay, not a full-featured mail-hosting server. It does not create hosted mailboxes for your domain. If an App Password was previously exposed or shared, revoke it and create a replacement if your Google account permits App Passwords. Never reuse credentials copied from old notes or logs.

1. Understand the final architecture

Plain text
OUTGOING
Visitor submits website form
        ↓
PHP application → ab_send_mail() → PHP mail()
        ↓
Local sendmail-compatible interface
        ↓
Postfix on Ubuntu 24.04
        ↓ authenticated SMTP + STARTTLS, port 587
smtp.gmail.com
        ↓
Recipient's mail server / inbox

INCOMING (separate flow)
Sender → [email protected]
        ↓
Cloudflare Email Routing
        ↓
Configured destination mailbox

Postfix handles local submission and queues messages if delivery cannot complete immediately. Its SMTP client connects to Gmail using authentication and TLS. Cloudflare Email Routing handles incoming forwarding; its MX records are not an outbound SMTP relay. Do not configure Postfix to send outbound mail to a Cloudflare MX hostname.

2. What the troubleshooting results mean

The troubleshooting notes found that PHP mail initially failed while the local mail transport was missing or incorrectly configured. Postfix was then installed and enabled, after which PHP returned bool(true) from mail(). Direct SMTP delivery to Gmail's receiving MX servers on TCP port 25 timed out, while connectivity checks to smtp.gmail.com on ports 587 and 465 succeeded. The selected design was to relay through Gmail SMTP on port 587.

ResultWhat it establishes
mail() returns truePHP's configured transport accepted the message for delivery; it does not prove receipt.
Postfix is activeThe local mail service is running, not that every message is deliverable.
TCP port 587 connectsThe server can establish a network connection to the relay.
Postfix logs status=sentThe next server accepted the message; Inbox placement is not guaranteed.
The test message appears in the destination inboxDelivery was observed for that particular test.

The project notes also describe using journalctl because /var/log/mail.log was unavailable, inspecting the Postfix queue, and investigating user confirmation emails separately from administrator notifications. A result for one message path does not prove that every application notification works.

PHP documents that a true return from mail() means the message was accepted for delivery, not necessarily delivered. See the PHP mail() manual.

3. Inspect the existing server before changing it

Connect to your Lightsail instance over SSH. Run these read-only checks first:

Bash / Shell
lsb_release -a
php -v
php -r 'var_dump(function_exists("mail"));'
php -r 'echo ini_get("sendmail_path"), PHP_EOL;'
command -v sendmail
command -v postfix
sudo systemctl status postfix --no-pager
sudo postqueue -p

These commands report the OS and PHP CLI versions, whether the function exists, the CLI sendmail path, available binaries, Postfix status and queued mail. If Postfix is not installed, the service command may report that the unit cannot be found.

CLI and website PHP can differ. CloudPanel may run the site through a different PHP version and PHP-FPM pool. Identify the site's PHP version, document root, pool user/group and logs in CloudPanel. Inspect the relevant FPM configuration instead of assuming the CLI settings match. For example, after changing the version and path to match your server:

Bash / Shell
sudo grep -E '^(user|group)[[:space:]]*=' /etc/php/8.3/fpm/pool.d/*.conf

The path above is illustrative. Use the PHP version and pool file actually serving your site. Back up /etc/postfix/main.cf and any existing authentication map before changing a production configuration.

4. Check outbound connectivity and port 25

Direct delivery normally requires the sending MTA to connect to the recipient domain's MX server on port 25. Authenticated submission to a relay instead uses the relay's submission port, commonly 587 with STARTTLS. The troubleshooting notes found port 25 timing out while Gmail submission ports were reachable.

Bash / Shell
nc -4 -vz gmail-smtp-in.l.google.com 25
nc -4 -vz smtp.gmail.com 587
nc -4 -vz smtp.gmail.com 465

If nc is missing, install it with sudo apt update && sudo apt install -y netcat-openbsd. A successful TCP connection does not verify credentials or send a message.

AWS documents an outbound port 25 restriction by default on Lightsail instances. That does not mean every possible email path is blocked: using a reachable authenticated relay on port 587 avoids direct-to-MX delivery on port 25. Do not open inbound port 587 simply to allow the server to make an outbound connection. See AWS's Lightsail port 25 guidance and the Lightsail firewall documentation.

5. Prepare Gmail SMTP authentication

Google may allow eligible accounts to authenticate with an App Password, but availability depends on account type and security settings. Do not use a regular Gmail password as a generic SMTP password, and do not assume every account can create App Passwords.

  1. Open Google Account Security.
  2. Review two-step verification and account policies.
  3. If App Passwords are available and appropriate, open the Google App Passwords page and create a dedicated credential.
  4. Store the new credential securely. Never include it in source code, screenshots, chat, shell history or public repositories.
  5. If App Passwords are unavailable, use a supported OAuth 2.0/XOAUTH2 implementation or a transactional email service rather than bypassing Google security controls.

Google explains restrictions in its App Password help article. If a credential has ever been exposed, revoke it before production use. The placeholder below is fictional and must be replaced with your own newly issued credential.

6. Install Postfix and required packages

Confirm whether Postfix is already installed and whether its configuration contains settings to preserve. On a new or deliberately prepared server, update package metadata and install Postfix plus the packages commonly used for SASL authentication and certificate trust:

Bash / Shell
sudo apt update
sudo apt install postfix libsasl2-modules ca-certificates

During Postfix configuration, Internet Site is a common starting choice for a system that sends mail directly or through a relay. Set the system mail name to your own domain where appropriate, for example example.com. This name does not create a hosted mailbox or authorize a custom sender.

On a production server, do not overwrite files or re-run configuration prompts without reviewing the existing setup. See Ubuntu's Postfix installation guide.

Bash / Shell
command -v sendmail
postconf mail_version
sudo systemctl enable --now postfix
sudo systemctl status postfix --no-pager

PHP's sendmail_path should point to a working sendmail-compatible interface. If PHP uses another transport or custom path, diagnose that before assuming Postfix receives messages.

7. Configure Postfix to relay through Gmail

Postfix uses a relay host to forward messages instead of looking up each recipient's MX record for direct delivery. Square brackets in [smtp.gmail.com] tell Postfix to use that host directly. The port must match the credential-map entry.

Bash / Shell
sudo cp -a /etc/postfix/main.cf /etc/postfix/main.cf.backup-$(date +%F-%H%M%S)
sudo nano /etc/postfix/sasl_passwd

Put one line in the credentials file, replacing the sample username and placeholder with your own account and a newly issued App Password if eligible:

Bash / Shell
[smtp.gmail.com]:587 [email protected]:REPLACE_WITH_NEW_APP_PASSWORD

Never paste a previously exposed password into this file. Save it, restrict access and build the lookup database:

Bash / Shell
sudo chown root:root /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
sudo chown root:root /etc/postfix/sasl_passwd.db
sudo chmod 600 /etc/postfix/sasl_passwd.db

Database filenames and permissions can vary with the configured map type. If your system uses another backend, check it with postconf -m and adapt the map. Postfix documents the format and why the raw credential file should be readable only by root in its SMTP client SASL guide.

Inspect existing settings, then configure the relay and client authentication/TLS parameters:

Bash / Shell
sudo postconf -e 'relayhost = [smtp.gmail.com]:587'
sudo postconf -e 'smtp_sasl_auth_enable = yes'
sudo postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
sudo postconf -e 'smtp_sasl_security_options = noanonymous'
sudo postconf -e 'smtp_sasl_tls_security_options = noanonymous'
sudo postconf -e 'smtp_tls_security_level = encrypt'
sudo postconf -e 'smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt'

Verify that the CA bundle exists. If the configured map is not a hash: map, use the matching map type. smtp_tls_security_level = encrypt requires TLS for the relay connection, appropriate for port 587 with STARTTLS. Do not disable certificate verification to work around a TLS error. See Postfix configuration parameters.

Do not blindly force IPv4. If logs show a specific IPv6 routing failure, compare IPv4 and IPv6 connectivity and correct the actual network issue. Changing inet_protocols can affect service behavior and requires validation and restart.

8. Validate and restart Postfix

Bash / Shell
sudo postfix check
sudo postconf -n
sudo systemctl restart postfix
sudo postfix status

postfix check reports structural or permission problems. Review postconf -n locally; do not publish unrestricted output if it contains private hostnames or other sensitive configuration. If validation reports errors, fix those first rather than repeatedly restarting. Confirm that the effective relay host is [smtp.gmail.com]:587 and that authentication and TLS settings match the credential map.

9. Test PHP email delivery

Use an existing application workflow or a controlled test script that calls PHP's native mail(). Choose a mailbox you control and identify the message as a test. Do not publish an unauthenticated endpoint that lets anyone send arbitrary email.

For an isolated CLI test, create a temporary PHP file in a private working directory, not the website's public document root:

Bash / Shell
nano /tmp/postfix-mail-test.php
<?php
$to = '[email protected]'; // Replace with a mailbox you control.
$subject = 'Postfix SMTP relay test';
$message = "This is a controlled test from Ubuntu 24.04.\\n";
$headers = [
    'From: Example Website <[email protected]>',
    'Content-Type: text/plain; charset=UTF-8'
];
$result = mail($to, $subject, $message, implode("\\r\\n", $headers));
var_dump($result);

Replace both example addresses with values permitted by your sending account. A custom-domain From address is not automatically authorized by Gmail; use an authorized sender. Run the test and inspect the queue and journal:

Bash / Shell
php /tmp/postfix-mail-test.php
sudo postqueue -p
sudo journalctl -u postfix --since "10 minutes ago" --no-pager

Remove the test file when finished:

Bash / Shell
rm /tmp/postfix-mail-test.php

The CLI test checks the CLI PHP configuration, not necessarily the PHP-FPM configuration used by the website. For the live website, test the existing form after confirming it calls the expected helper and that the helper calls mail().

10. Inspect and manage the queue safely

List queued messages with sudo postqueue -p. If a message is deferred, identify its queue ID and inspect it with:

Bash / Shell
sudo postcat -q QUEUE_ID

Replace QUEUE_ID with the actual identifier. Queue content can include recipient addresses, subjects and message bodies, so redact it before sharing. Use logs to identify authentication failure, TLS failure, DNS trouble, temporary provider rejection or a recipient-specific error.

Do not delete the entire queue as a routine step. If deletion is necessary, identify the exact messages and queue IDs first. sudo postsuper -d QUEUE_ID permanently removes that queued message. Use it only when you have confirmed the message should not be retried. Bulk queue deletion is destructive and may discard legitimate notifications.

11. Understand sender identity and Reply-To

Email has several identities that should not be confused:

  • SMTP authentication identity: the Gmail account used to log in.
  • Envelope sender: the address used in the SMTP delivery envelope and often for bounces.
  • From header: the visible sender shown by email clients.
  • Reply-To: the address used when a recipient clicks Reply.
  • Recipient: the destination address.

For a visitor's discount request, the administrator notification should generally use an authorized site address such as [email protected] as From, while setting Reply-To to the visitor's submitted address. Validate user input; never insert raw form input into email headers. Authenticating with Gmail does not automatically authorize sending as every address on your domain. Verify a permitted “Send mail as” identity where supported or use a provider configured for your domain. Do not spoof a sender or assume Gmail will preserve an unauthorized From header.

12. Verify Cloudflare Email Routing separately

Cloudflare Email Routing handles incoming messages. Check the domain's MX records:

Bash / Shell
dig MX example.com +short

Replace example.com with your domain and compare the results with the active Cloudflare Email Routing configuration. Do not replace existing MX records with guessed values; use the records Cloudflare provides. See the Cloudflare Email Routing documentation.

Test inbound forwarding separately by sending a message from an external mailbox to the configured alias. Check the forwarding destination's Inbox and Spam folders. If Postfix logs show relay acceptance but the incoming alias does not forward messages, investigate the Cloudflare route and destination mailbox rather than changing the outbound SMTP relay.

13. Troubleshoot the application workflow

A discount-request workflow may send two separate messages: a confirmation to the visitor and an administrator notification to [email protected]. If one arrives and the other does not, diagnose each message independently.

  1. Inspect the actual return value from ab_send_mail() and determine whether it calls PHP's mail().
  2. Submit one fresh test request while watching the Postfix journal.
  3. Match log timestamps and queue IDs to the exact message.
  4. Check recipient, sender, relay response and final Postfix status.
  5. Check the recipient's Spam folder and, for inbound aliases, the Cloudflare forwarding destination.
  6. Log failure reasons without passwords, full message bodies, unnecessary personal information or authentication tokens.

Do not rewrite mailer.php or redesign the AJAX request path merely because an email fails. Inspect the relevant source lines and call chain first. A working visitor confirmation does not prove the administrator notification uses the same recipient, sender, branch or helper call.

14. SPF, DKIM, DMARC and production limits

SPF identifies authorized sending systems for a domain; DKIM adds a cryptographic signature; DMARC applies policy and reporting around SPF/DKIM alignment. Records depend on the actual outbound provider and domain configuration. Do not copy a generic SPF value, create a second SPF record or invent a DKIM selector. Review all services that send mail for the domain before changing DNS.

Cloudflare Email Routing's records for incoming forwarding are not proof that application mail sent through Gmail is correctly authenticated. A test message reaching one inbox does not establish long-term deliverability. Review message headers and provider guidance for the exact sender arrangement. Google imposes account and service limits, and a personal Gmail account may not be the right long-term relay for growing transactional volume. If you need application-focused delivery metrics, bounce handling or scale, evaluate a transactional provider such as Amazon SES. SES has its own identity-verification, region, quota and sandbox requirements; see the SES production-access guide.

15. Monitoring and maintenance checklist

  • Check service health with sudo systemctl status postfix --no-pager.
  • Review queue size with sudo postqueue -p.
  • Review recent events with sudo journalctl -u postfix --since "1 hour ago" --no-pager.
  • Investigate repeated SASL authentication and TLS errors.
  • Keep Gmail account recovery and two-step verification secure.
  • Rotate credentials if exposed, suspected compromised or no longer needed.
  • Review SPF, DKIM and DMARC when the sending provider or domain configuration changes.
  • Monitor application-side failures from ab_send_mail().
  • Watch for unexpected recipients, form abuse and unusual queue growth.
  • Keep Ubuntu packages and the server control panel updated.

A running service and an empty queue are useful health signals, but neither independently proves that every email reached the intended Inbox.

Troubleshooting table

SymptomLikely causeDiagnostic commandRecommended action
mail() returns falseTransport missing, incorrect sendmail path or local rejectionphp -r 'echo ini_get("sendmail_path"), PHP_EOL;'Check website PHP-FPM settings and Postfix installation.
mail() returns true, but no email arrivesDeferred delivery, relay rejection, spam filtering or wrong recipientsudo journalctl -u postfix --since "10 minutes ago" --no-pagerMatch logs to the test and inspect the queue and destination folders.
Port 25 times outOutbound restriction or network path problemnc -4 -vz gmail-smtp-in.l.google.com 25Use a reachable authenticated relay or follow AWS's request process if direct delivery is required.
Port 587 unreachableDNS, route, firewall or egress issuenc -vz smtp.gmail.com 587Check connectivity and firewall direction.
Gmail authentication failsIncorrect/revoked credential or account policysudo journalctl -u postfix --since "10 minutes ago" --no-pagerCheck account eligibility and replace exposed credentials. Never print passwords.
TLS certificate validation failsMissing CA bundle, incorrect system time or TLS configurationls -l /etc/ssl/certs/ca-certificates.crtRepair CA trust and verify time and relay settings. Never disable TLS verification.
Messages remain queuedTemporary failure, authentication issue or recipient rejectionsudo postqueue -pInspect the queue ID and logs before retrying or deleting.
status=sent, but recipient cannot find itRelay accepted the message; later filtering may differsudo journalctl -u postfix --since "30 minutes ago" --no-pagerCheck Spam, search folders and inspect headers.
Admin notification fails, visitor confirmation worksDifferent recipient, branch, sender or helper invocationWatch the journal while submitting one controlled requestInspect the application call path and test both messages separately.
Custom From is rejected or rewrittenSender identity not authorized by GmailReview SMTP rejection in the Postfix journalUse an authorized sender or verified domain-sending provider; set Reply-To separately.
Cloudflare forwarding failsIncorrect route, unverified destination or MX issuedig MX example.com +shortCheck the Cloudflare dashboard, destination verification and Spam folder.
Spam submissions enter queuePublic form abuse or inadequate rate limitingsudo postqueue -pAdd validation, rate limiting, bot protection and monitoring.
/var/log/mail.log is missingLogging uses systemd journal or another setupsudo journalctl -u postfix --since "1 hour ago" --no-pagerUse the configured log destination; a missing file does not mean Postfix is broken.

Frequently asked questions

Does Postfix replace PHP's mail() function?

No. PHP can continue calling mail(); Postfix supplies the local sendmail-compatible transport and relays messages onward.

Does Cloudflare Email Routing send outgoing mail?

Not by itself. It forwards incoming mail. Postfix needs a separate outbound relay such as Gmail SMTP.

Does status=sent guarantee Inbox delivery?

No. It indicates the next server accepted the message. Filtering and final placement happen later.

Should I delete the Postfix queue to fix email?

No. Inspect the queue and logs first. Delete only identified messages that should not be retried.

Do I need to rewrite my PHP mail helper?

Not necessarily. First confirm the existing helper calls mail() and the configured sendmail-compatible transport is Postfix.

Conclusion

For an existing PHP website on AWS Lightsail, Postfix can preserve the application's native mail() workflow while relaying outbound email through Gmail SMTP on port 587. Separate local submission, relay authentication, final delivery and incoming forwarding into distinct checks.

Back up the configuration, protect the SMTP credential map, require TLS, validate Postfix before restarting, and use controlled tests with a mailbox you own. Keep Cloudflare Email Routing focused on incoming mail, and inspect the actual application path before changing a working mail helper. Treat logs and SMTP acceptance as diagnostic evidence—not a guarantee that every message reached the recipient's Inbox.

Official references

Found this useful?Share it with someone who might enjoy it.