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
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.
| Result | What it establishes |
|---|---|
mail() returns true | PHP's configured transport accepted the message for delivery; it does not prove receipt. |
| Postfix is active | The local mail service is running, not that every message is deliverable. |
| TCP port 587 connects | The server can establish a network connection to the relay. |
Postfix logs status=sent | The next server accepted the message; Inbox placement is not guaranteed. |
| The test message appears in the destination inbox | Delivery 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:
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:
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.
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.
- Open Google Account Security.
- Review two-step verification and account policies.
- If App Passwords are available and appropriate, open the Google App Passwords page and create a dedicated credential.
- Store the new credential securely. Never include it in source code, screenshots, chat, shell history or public repositories.
- 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:
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.
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.
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:
Never paste a previously exposed password into this file. Save it, restrict access and build the lookup database:
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:
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
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:
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:
Remove the test file when finished:
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:
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:
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.
- Inspect the actual return value from
ab_send_mail()and determine whether it calls PHP'smail(). - Submit one fresh test request while watching the Postfix journal.
- Match log timestamps and queue IDs to the exact message.
- Check recipient, sender, relay response and final Postfix status.
- Check the recipient's Spam folder and, for inbound aliases, the Cloudflare forwarding destination.
- 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
| Symptom | Likely cause | Diagnostic command | Recommended action |
|---|---|---|---|
mail() returns false | Transport missing, incorrect sendmail path or local rejection | php -r 'echo ini_get("sendmail_path"), PHP_EOL;' | Check website PHP-FPM settings and Postfix installation. |
mail() returns true, but no email arrives | Deferred delivery, relay rejection, spam filtering or wrong recipient | sudo journalctl -u postfix --since "10 minutes ago" --no-pager | Match logs to the test and inspect the queue and destination folders. |
| Port 25 times out | Outbound restriction or network path problem | nc -4 -vz gmail-smtp-in.l.google.com 25 | Use a reachable authenticated relay or follow AWS's request process if direct delivery is required. |
| Port 587 unreachable | DNS, route, firewall or egress issue | nc -vz smtp.gmail.com 587 | Check connectivity and firewall direction. |
| Gmail authentication fails | Incorrect/revoked credential or account policy | sudo journalctl -u postfix --since "10 minutes ago" --no-pager | Check account eligibility and replace exposed credentials. Never print passwords. |
| TLS certificate validation fails | Missing CA bundle, incorrect system time or TLS configuration | ls -l /etc/ssl/certs/ca-certificates.crt | Repair CA trust and verify time and relay settings. Never disable TLS verification. |
| Messages remain queued | Temporary failure, authentication issue or recipient rejection | sudo postqueue -p | Inspect the queue ID and logs before retrying or deleting. |
status=sent, but recipient cannot find it | Relay accepted the message; later filtering may differ | sudo journalctl -u postfix --since "30 minutes ago" --no-pager | Check Spam, search folders and inspect headers. |
| Admin notification fails, visitor confirmation works | Different recipient, branch, sender or helper invocation | Watch the journal while submitting one controlled request | Inspect the application call path and test both messages separately. |
| Custom From is rejected or rewritten | Sender identity not authorized by Gmail | Review SMTP rejection in the Postfix journal | Use an authorized sender or verified domain-sending provider; set Reply-To separately. |
| Cloudflare forwarding fails | Incorrect route, unverified destination or MX issue | dig MX example.com +short | Check the Cloudflare dashboard, destination verification and Spam folder. |
| Spam submissions enter queue | Public form abuse or inadequate rate limiting | sudo postqueue -p | Add validation, rate limiting, bot protection and monitoring. |
/var/log/mail.log is missing | Logging uses systemd journal or another setup | sudo journalctl -u postfix --since "1 hour ago" --no-pager | Use 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
- Ubuntu Server: Install and configure Postfix
- Postfix: SMTP client SASL authentication
- Postfix: Configuration parameters
- PHP manual: mail()
- Google Account Help: App Passwords
- Google Account Security
- Google App Passwords page
- AWS: Remove the Lightsail port 25 restriction
- AWS Lightsail: Firewalls and port mappings
- Cloudflare Email Routing documentation
- Amazon SES: Request production access

By Amit Das