A custom PHP website may need to send password-reset links, account confirmations, contact-form notifications, and other transactional messages. Configuring SMTP gives the application a defined route for submitting those messages instead of relying on an unconfigured local mail transport.
This tutorial uses AWS Lightsail, Ubuntu 24.04, CloudPanel, Cloudflare DNS and Email Routing, PHP, Composer, PHPMailer, and Gmail SMTP as an example. The example domain is example.com; replace it with your own domain and paths. CloudPanel layouts and PHP-FPM users can differ, so verify your installation before changing files.
The central distinction is simple: Cloudflare Email Routing forwards incoming messages; Gmail SMTP sends outgoing messages. These are separate services.
How the Components Work Together
- AWS Lightsail provides the virtual server.
- Ubuntu 24.04 is the operating system.
- CloudPanel manages websites and PHP settings.
- Cloudflare DNS and Email Routing manage DNS and forward incoming messages to a destination inbox.
- Gmail SMTP submits outgoing messages.
- PHPMailer formats messages and handles the SMTP connection.
- Composer installs PHP libraries and generates the autoloader.
- The environment file stores settings and credentials where the web server cannot publicly serve them.
Cloudflare Email Routing does not create a conventional mailbox with a password for outbound SMTP. Do not use an MX hostname such as route3.mx.cloudflare.net as a replacement for smtp.gmail.com. Cloudflare documents Email Routing as a way to forward incoming messages. Cloudflare also has a separate Email Service product, which is a different configuration. See the Cloudflare Email Routing documentation and Cloudflare Email Service documentation.
What You Need Before Starting
- Access to your Lightsail instance and SSH or console access.
- Administrative permissions for carefully selected server changes.
- A functioning Ubuntu 24.04 server and website.
- CloudPanel access to identify the site's document root, PHP version, PHP-FPM pool, and logs.
- A working PHP application and its existing mail workflow.
- Composer and PHPMailer, or a safe process for adding them.
- A Google account that supports an authentication method the application can use.
- Access to Cloudflare DNS if the domain uses Cloudflare.
- A backup of relevant application configuration and Composer files.
Never publish SMTP passwords, Google App Passwords, OAuth tokens, private keys, or environment files. Do not paste secrets into screenshots, public repositories, support forums, or logs.
Gmail SMTP vs Cloudflare Email Routing
| Feature | Gmail SMTP | Cloudflare Email Routing |
|---|---|---|
| Purpose | Submits outgoing messages | Forwards incoming messages |
| Authentication | Uses a Google-supported method, such as OAuth 2.0; App Passwords may be available to eligible accounts | Does not provide a normal outbound SMTP mailbox credential through Email Routing |
| PHP sending | Yes, if authentication, sender permissions, and usage comply with account requirements | Not through Email Routing alone |
| Domain configuration | Requires a permitted sender identity and appropriate sending setup | Requires incoming-routing rules and associated DNS configuration |
Google documents smtp.gmail.com as the outgoing SMTP hostname. For STARTTLS, use port 587; port 465 is used for implicit SSL/TLS. This guide uses port 587 with STARTTLS. See Google's Gmail IMAP, POP, and SMTP documentation.
Step 1 — Check Your Google Account Authentication
Do not rely on old tutorials that tell you to use your regular Google password in a third-party PHP application. Google's documentation supports OAuth 2.0 for Gmail clients and recommends “Sign in with Google” where the application supports it. App Passwords remain available to some accounts, but not all.
- Open Google Account Security.
- Review your account's two-step verification and security settings.
- If App Passwords are available and suitable, visit Google App Passwords.
- Create a dedicated App Password for the website and store it securely.
- Use it only if the mailer is configured for that authentication method.
An App Password is not your regular Google password. Google says App Passwords require 2-Step Verification and may be unavailable for accounts using security keys only, accounts managed by a work or school organization, or accounts enrolled in Advanced Protection. App Passwords may be revoked after the account password changes. Read Google's current App Password guidance.

If App Passwords are unavailable, do not bypass an organization's policies or seek an obsolete “less secure apps” workaround. Use a supported OAuth 2.0/XOAUTH2 implementation or choose an email service designed for application sending. PHPMailer supports XOAUTH2, but this requires OAuth setup and dependencies; a normal password in an environment file is not OAuth.
Step 2 — Choose a Permitted Sender Address
Keep three identities distinct:
- SMTP username: the full Google account address used to authenticate.
- From address: the address recipients see.
- Reply-To address: the address where replies should go.
For this example, use [email protected] as the SMTP username, [email protected] as the intended From address, and [email protected] as Reply-To. These are illustrative addresses, not preconfigured mailboxes.
Gmail does not automatically authorize every custom-domain address just because you control its DNS. Depending on the account and sending method, you may need to add and verify the address in Gmail's “Send mail as” settings. Follow the current Google instructions and complete any required verification.
Cloudflare Email Routing may forward a verification message if the alias and route already exist. That does not create a mailbox or automatically authorize outbound sending. If Google rejects the custom-domain From address, test with the authenticated Gmail address first, then verify the custom sender according to the account's rules.
Step 3 — Create the SMTP Environment File
The example path is:
This path is specific to the example. Confirm the site's actual document root and filesystem layout in CloudPanel. The file should be outside the public document root so a web request cannot download it. If your layout differs, select a secure path the application can read but the web server cannot serve publicly.
Add placeholder values such as:
Replace placeholders with your own values. Never publish a file containing a real password.
| Key | Purpose |
|---|---|
MAIL_METHOD | An application-specific switch; it works only if your code checks it. |
SMTP_HOST | SMTP hostname, here smtp.gmail.com. |
SMTP_PORT | SMTP port, here 587 for STARTTLS. |
SMTP_USERNAME | Account identity for the chosen authentication method. |
SMTP_PASSWORD | A supported credential, such as an App Password if eligible. |
SMTP_ENCRYPTION | An application-specific value that must map to STARTTLS in the mailer. |
SMTP_FROM_EMAIL, SMTP_FROM_NAME | Intended sender address and display name. |
MAIL_FROM_EMAIL, MAIL_FROM_NAME | Alternative application-level sender keys; retain them only if the code expects them. |
MAIL_REPLY_TO | Intended Reply-To address. |
Creating the file alone does not configure PHP. The application must explicitly read it or load it through an environment library, then pass the values into PHPMailer. The keys must match what the actual mailer expects. Avoid introducing a second configuration system before checking the existing code.
Step 4 — Protect the Environment File
File permissions must match the real PHP-FPM runtime user and group. Some CloudPanel installations use a site-specific system user rather than www-data. Verify the pool before applying this example:
In this example, the owner is root, the group is www-data, and mode 640 grants the owner read/write access, the group read access, and no access to other users. This works only if the PHP process has the required group access.
CloudPanel documents PHP-FPM pools under a path shaped like /etc/php/$PHP_VERSION/fpm/pool.d/. Inspect the pool actually serving your site; do not assume every installation uses the same user. For example, after replacing the version and path with the correct values, an administrator might inspect pool settings with:
This is an example only: your PHP version and pool filename may differ. Review the output carefully if several pools exist. Do not dump the environment file or print its password to test access. Use a restricted diagnostic or existing application check, and remove temporary diagnostic code afterward.
Never use chmod 777 to fix a permission problem. Find the real runtime identity and grant only the access required.
Step 5 — Verify Composer and PHPMailer
PHPMailer handles SMTP and message formatting. Composer installs it and creates the autoloader. Back up composer.json, composer.lock, and deployment configuration before changing dependencies on a production website.
Check whether the autoloader exists:
Its existence does not prove PHPMailer is installed. Check the package from the project's actual directory:
If the package is missing, inspect the dependency setup and test in staging if possible. Only when you are in the correct project directory and the package is not already installed should you consider:
This changes project dependency files and installs the package. Do not run it blindly on a live site: dependency changes can affect the application, and file ownership may differ depending on which user runs Composer. Review the change, confirm PHP compatibility, and deploy through the normal process. See the Composer documentation and PHPMailer's official repository.
Step 6 — Confirm That the Mailer Reads the Configuration
The example mailer path is:
The actual file has not been independently inspected here, so do not replace it with a guessed implementation. Check that it:
- Loads the correct Composer autoloader.
- Reads the environment file from the intended path.
- Uses the configured Gmail host, port, encryption, username, and credential.
- Authenticates using a method supported by the Google account.
- Uses a permitted From address and sets the intended Reply-To address.
- Logs useful errors without logging passwords, tokens, or other secrets.
- Is the mailer actually called by the form or workflow being tested.
In PHPMailer, STARTTLS is commonly configured with PHPMailer::ENCRYPTION_STARTTLS, but the application may translate its environment values differently. Confirm how the existing code interprets SMTP_ENCRYPTION=tls. Read the PHPMailer documentation wiki for examples and troubleshooting.
Step 7 — Test Connectivity to Gmail SMTP
Before debugging credentials, test whether the server can open a TCP connection to Gmail on port 587:

If nc is missing, Ubuntu's netcat-openbsd package provides it:
Installing a package changes the server, so follow your maintenance process. A successful result usually says that the connection to smtp.gmail.com on port 587 succeeded, though exact wording varies.
A successful TCP connection means the hostname resolved and a network connection was established. It does not prove that Google credentials work, the From address is authorized, the message is accepted, or the recipient's Inbox will receive it.
A timeout may indicate a network or routing issue. A connection refusal points to a different failure at the destination or along the path. A DNS error requires checking hostname spelling and resolver behavior. Investigate the actual output rather than treating every failure alike.
Do not open inbound port 587 in Lightsail simply because the website connects outbound to Gmail. Inbound firewall rules govern traffic arriving at the instance. AWS documents a default restriction on outbound port 25 for Lightsail, which is different from port 587. See AWS's Lightsail port 25 guidance. If port 587 fails, diagnose the real network and account conditions rather than assuming the port-25 restriction is the cause.
Step 8 — Send a Controlled Test Email
- Save the configuration file with the correct values and restricted permissions.
- Confirm that the application loads the expected mailer.
- Use an existing form or restricted test endpoint that calls that mailer.
- Send to a mailbox you control or are authorized to test.
- Check Inbox, Spam, and other relevant folders.
- If delivery fails, inspect the correct PHP-FPM or application logs.
- Remove or disable temporary diagnostic endpoints immediately after testing.
Option A — Send a test email directly from the terminal
If you want to test Gmail SMTP authentication and delivery independently of your website code, you can use a temporary Python script. This helps separate a Google SMTP problem from a PHPMailer or application-configuration problem. The script below uses smtp.gmail.com, port 587, and STARTTLS, and prompts for the App Password without displaying it or placing it in the shell command.
First, confirm that the server can reach Gmail SMTP:
If nc is not installed, install Ubuntu's netcat-openbsd package as described in Step 7. A successful TCP connection confirms basic reachability only; it does not test authentication or send a message.
Check whether Python 3 is installed:
If it is missing, install it using your server's normal package-maintenance process:
Create a temporary test script:
Paste this code into the file:
Save the file and exit the editor. Then run:
Enter the full Gmail address used for SMTP authentication, a recipient address you control or are authorized to test, and the Google App Password when prompted. The password prompt does not echo the password. Use a Google App Password only if your account supports it; do not enter your regular Google account password. If App Passwords are unavailable, use a supported OAuth 2.0/XOAUTH2 implementation or another transactional email provider.
If the script prints SUCCESS, the server authenticated to Gmail SMTP and handed the test message to the SMTP service. Check the recipient's Inbox, Spam, and other relevant folders. This result does not guarantee inbox placement or validate the website's own PHPMailer settings.
Remove the temporary script after testing:
The script contains no saved password, but removing it is still good housekeeping. Do not add real credentials to the script or share terminal output that contains private information.
Option B — Test the website's actual PHPMailer configuration
The Python test above verifies the basic Gmail SMTP authentication and sending path independently. To confirm that your website works, also test through the actual PHP mailer that reads your environment file. Navigate to the real project directory identified in CloudPanel; this example path may not match your server:
Use an existing form or a restricted, temporary test endpoint that calls the same mailer and configuration used by the website. Send to a mailbox you control, then inspect the relevant PHP-FPM or application logs if it fails. Do not create a public endpoint that accepts arbitrary recipient addresses. If you must create a separate test script, restrict it with authentication or an IP allowlist, use a fixed recipient, avoid displaying secrets, and remove it immediately after testing.
If the Python test succeeds but the website test fails, check whether the application loads the intended environment file, whether its variable names match the code, whether PHP-FPM can read the file, whether PHPMailer is using port 587 with STARTTLS, and whether the configured sender address is authorized. A successful Python test alone does not prove that the website's PHP configuration, PHP-FPM environment, or PHPMailer settings are correct.
An existing subscription form is useful only if its workflow actually calls the mailer you changed. A successful form submission may mean only that the form data was saved; it does not necessarily prove that an email was sent.
Never expose a public diagnostic script that accepts arbitrary recipient addresses and sends email. It can become an abuse endpoint. If a separate test script is unavoidable, restrict access with authentication or an IP allowlist, use a fixed recipient, do not reveal secrets, and remove the script immediately after testing.
The supplied setup notes report that a message reached a Gmail inbox after the environment file was added. This is a reported result for that configuration, not independent proof of every authentication, sender-authorization, DNS, or long-term deliverability setting.
Step 9 — Find the Correct Logs
This command is sometimes used during mail troubleshooting:
It is useful only if a local mail service writes relevant events to that file. PHPMailer connecting directly to Gmail SMTP may report errors in PHP or application logs rather than Postfix's log. A missing /var/log/mail.log does not by itself mean direct SMTP is broken.
CloudPanel provides a log viewer for NGINX and PHP-FPM. Its documentation describes site logs under a path shaped like /home/$siteUser/logs/; exact filenames and paths depend on the installation. Use the CloudPanel log viewer for the correct domain or inspect the actual site's logs. See CloudPanel's log documentation.
Before sharing logs, redact passwords, tokens, authorization headers, personal information, and sensitive message content. Include the timestamp, error type, relevant non-secret context, and the action that triggered the error—not the credential.
Troubleshooting Common SMTP Errors
| Problem | Possible cause | Recommended check |
|---|---|---|
| Connection timeout | DNS, routing, outbound connectivity, or network policy | Check hostname resolution and TCP connectivity; confirm the network path. |
| Authentication failed | Wrong credential or unsupported authentication method | Review the Google account's supported sign-in methods; do not assume a normal password will work. |
| App Password rejected | Feature unavailable, mistyped/revoked credential, or account restriction | Review Google Account Security and generate a new one only if permitted. |
| Sender address rejected | From address is not authorized | Test with the authenticated Gmail address and verify the custom sender. |
| Configuration file not found | Wrong path or loading logic | Verify the exact path and that the running mailer reads the file. |
| Permission denied | PHP-FPM cannot read the file or a parent directory | Check the actual pool user/group and grant minimal required access. |
| PHPMailer class not found | Missing dependency or wrong autoloader | Check Composer package status and the autoloader path. |
| Email goes to Spam | Authentication alignment, sender reputation, content, or recipient filtering | Inspect message headers and verify the provider's SPF, DKIM, and DMARC setup. |
| Configuration change has no effect | Another mailer, stale configuration, or alternate delivery path | Trace the actual code path and inspect running application's logs. |
| Old Postfix messages remain queued | Earlier messages used a separate local mail transport | Inspect the queue and deliberately decide whether to retry, migrate, or remove messages; do not flush blindly. |
Change one thing at a time and repeat a controlled test. No single fix is guaranteed to solve every SMTP error.
Configure SPF, DKIM and DMARC Carefully
- SPF is a DNS policy that identifies sending systems authorized to send for a domain.
- DKIM adds a cryptographic signature that lets receiving systems verify a domain's signature and signed message content.
- DMARC publishes a policy for handling messages that fail SPF/DKIM alignment checks and can enable reporting.
Cloudflare Email Routing does not prove that outgoing PHP mail from example.com is authenticated. If Gmail sends your application mail, follow Google's current requirements for the authenticated account and custom sender. If you use another provider, obtain DNS values from that provider. Do not copy records from an unrelated tutorial.

Inspect existing records before editing DNS and identify all services that legitimately send mail for the domain. Do not create multiple conflicting SPF TXT records; replacing an existing record without accounting for other senders can break their mail. DKIM records are provider-specific, and a DMARC policy should reflect the domain's real sending setup. See Cloudflare's email DNS records guide.
This guide does not claim that SPF, DKIM, or DMARC for example.com has been checked or configured correctly. Verify live records and inspect message headers before drawing that conclusion.
Gmail SMTP vs Amazon SES vs Another Transactional Provider
| Consideration | Gmail SMTP | Amazon SES | Other transactional provider |
|---|---|---|---|
| Initial setup | Can be straightforward for an eligible account, but authentication and sender rules matter | Requires AWS setup, identity verification, and region/account configuration | Varies; often requires domain verification and API or SMTP credentials |
| Domain sending | Depends on sender permissions and Google's rules | Domain or address identities must be verified | Usually supported after provider-specific verification |
| Transactional use | Can suit testing or modest use where account terms allow | Designed for application email delivery | Often designed for password resets, receipts, and alerts |
| Limits | Google service and account limits apply | Sandbox restrictions and quotas may apply | Depends on provider, plan, and account status |
| Cost | Depends on account/service arrangement | Review current pay-as-you-go or plan pricing | May use free tiers, subscriptions, or usage-based fees |
| Monitoring | Application logs and provider feedback may be needed | AWS offers metrics and related tools depending on setup | May provide delivery events, bounce handling, and dashboards |
Gmail SMTP can be convenient for testing or low-volume use where Google's rules permit it. For production websites with growing transactional volume, evaluate a provider designed for application email so you can manage sender identities, bounces, complaints, and delivery events. No provider can guarantee every message reaches the Inbox.
Amazon SES is worth evaluating for an AWS-hosted website, but Lightsail does not automatically configure SES or grant production sending access. AWS says new SES accounts start in the sandbox in each region; restrictions include sending only to verified addresses or the mailbox simulator until production access is granted. Read SES production access guidance and SES identity verification. Review the current Amazon SES pricing page before choosing a service.
Security and Maintenance Checklist
- Keep SMTP credentials, App Passwords, and OAuth tokens private.
- Store secrets outside the public document root where possible.
- Use restrictive permissions and verify the PHP-FPM runtime user/group.
- Never commit credentials to Git or expose them in screenshots and backups.
- Avoid printing secrets in terminal output, pages, or logs.
- Keep Ubuntu, PHP, Composer, and dependencies updated.
- Review dependency changes before production deployment.
- Monitor sending errors and unusual activity.
- Remove temporary diagnostic scripts after testing.
- Verify sender authorization and domain-authentication records.
- Revoke or rotate exposed or obsolete credentials.
- Check provider limits before using SMTP for bulk newsletters.
Frequently Asked Questions
What is the Gmail SMTP server address?
Use smtp.gmail.com. Google's documentation lists port 587 for TLS/STARTTLS and port 465 for implicit SSL/TLS.
Which port should I use on Ubuntu?
For this STARTTLS setup, use port 587. Outbound connectivity and account authentication must also work.
Can Cloudflare Email Routing send messages from PHP?
Not by itself. It forwards incoming messages. PHP needs a separate outbound provider, such as Gmail SMTP. Cloudflare's separate Email Service is a different product.
Can I use my regular Gmail password?
Do not assume so. Use a Google-supported authentication method. App Passwords are available only to eligible accounts, while OAuth 2.0 is recommended where supported.
What if App Passwords are unavailable?
Use supported OAuth 2.0/XOAUTH2 or a transactional provider. Follow organization policy rather than bypassing restrictions.
Does creating an environment file configure PHP automatically?
No. The code must read the file and pass its values to PHPMailer.
Why can the server connect but still fail to send?
A TCP connection checks basic reachability only. Authentication, sender permission, configuration loading, or provider rejection can still prevent sending.
Why does Gmail reject my custom-domain From address?
The address may not be authorized for the authenticated account. Verify it according to Google's rules or test with the authenticated Gmail address first.
Do I need an inbound port 587 rule in Lightsail?
Usually not for an outbound client connection. Inbound rules do not solve an outbound connectivity problem.
Why does the message go to Spam?
Reputation, content, authentication alignment, recipient filtering, and provider policies all matter. Inspect headers and DNS authentication; SMTP acceptance does not guarantee Inbox placement.
Will Gmail SMTP resend old Postfix messages?
No. Messages already queued by a local mail service are separate. Inspect the queue and decide how to handle it deliberately.
Should I use Gmail SMTP or Amazon SES?
It depends on volume, terms, monitoring needs, and operational requirements. Gmail may suit permitted low-volume use; SES and other transactional providers are designed for application sending. Compare current limits, verification steps, sandbox status, and costs.
Final Thoughts
To configure Gmail SMTP on Ubuntu 24.04 safely, confirm your account's supported authentication method, verify sender permissions, protect the environment file, and make sure the existing mailer actually reads it. Test outbound connectivity, send a controlled message to an inbox you own, and inspect the correct logs if something fails.
Keep Cloudflare Email Routing and Gmail SMTP separate in your design: one forwards incoming messages, while the other submits outgoing messages. A test message arriving is a useful milestone, but it does not prove complete sender authorization, SPF/DKIM/DMARC configuration, or long-term deliverability.
Official References
- Google: Gmail IMAP, POP, and SMTP
- Google: App Passwords
- Google Account Security
- Google App Passwords page
- PHPMailer official repository
- PHPMailer documentation wiki
- Composer documentation
- AWS Lightsail documentation
- AWS: Lightsail outbound port 25 guidance
- Cloudflare Email Routing documentation
- Cloudflare Email Service documentation
- Cloudflare DNS email records guide
- CloudPanel logs documentation
- CloudPanel domains and PHP-FPM pool documentation
- Amazon SES production access
- Amazon SES identity verification
- Amazon SES pricing

By Amit Das