Out-Bound Gmail Support in Ubuntu Server (Ubuntu 16/18/20/22+)
3,696 Total views across this article’s versions; includes the historical baseline where available.
When I’m writing BaSH or SHell scripts - especially when it comes to scripts designed to monitor operational processes - I often find it useful to setup an automated alert system via email. I use Gmail exclusively for my personal email use, and have my account mirrored across multiple devices. So, when something occurs that I need to know about, it’s a straight-forward and simple way to get my attention. But, how does one get an Ubuntu server to send email to one’s Gmail account? Unfortunately, that is not so straight-forward.
Email transport uses Simple Mail Transfer Protocol (SMTP), not Simple Network Management Protocol (SNMP). An Ubuntu host can submit locally generated alerts through an authenticated Gmail account without hosting a public mailbox service. Postfix acts as the local mail-transfer agent and sends those messages to Gmail’s submission server.
This is a dedicated outbound-host example. Before adapting it on an existing mail server, preserve its configuration and account for services that already depend on it. Ubuntu 16.04/18.04 are historical targets; verify the release/package’s current maintenance coverage. The documentation and message examples were reviewed locally, but an Ubuntu installation and real Gmail delivery were not rerun. Ubuntu release lifecycle.
Mail Relays
SMTP server-to-server delivery commonly uses TCP port 25. Authenticated message submission is a distinct role, conventionally using port 587 with STARTTLS; port 465 is also used for implicit TLS. Whether an ISP blocks port 25 does not define the protocol or prove Gmail “moved” all its mail servers to 587. Message submission standard.
This example uses [smtp.gmail.com]:587. It is different from Google Workspace’s separately administered smtp-relay.gmail.com service. Account eligibility, sender rules and sending limits still apply. Google’s SMTP options.
Postfix
Postfix provides a mail queue, an SMTP client/server and a Sendmail-compatible command-line submission interface. Here, its SMTP client authenticates to Gmail using SASL over TLS.
Postfix’s sendmail command is not the separate Sendmail 8.x mail-server product. Nor does Postfix create “SSL hashes” of Gmail credentials: its lookup database must retain credentials that can be used to authenticate. The security requirements are restricted local access and a correctly authenticated TLS connection to the relay. A self-signed client certificate is not needed for this app-password example. Postfix SASL documentation.
Install Postfix
On a supported Ubuntu host, install the mail software, SASL mechanism modules and trusted CA bundle:
sudo apt update
sudo apt install postfix libsasl2-modules ca-certificates
For a host whose mail should all go to a relay, the installer’s Satellite system role is a closer match than a public Internet-site configuration. If asked for a relay, use [smtp.gmail.com]:587. Supply the appropriate system mail name; it qualifies unqualified sender/recipient addresses and is not an irrelevant field to leave blank arbitrarily.
The installation dialogue depends on package version, selected role, existing settings and the debconf frontend. It can be a text-terminal dialogue; it is not necessarily a graphical application. Existing installations can be configured without assuming every prompt will appear. Ubuntu package’s installer questions; Ubuntu SASL modules package.
Ubuntu 22.04+
Ubuntu 22.04 is not a universal boundary at which Postfix suddenly needs a particular extra set of prompts. Follow the installed package’s options and the intended mail role. The underlying settings below matter more than matching screenshots from one installation. Consult the Ubuntu Postfix guide for distribution-specific service details.
Say Goodbye to Gmail’s Less-Secure App Support
Do not configure this recipe with your ordinary Google account password or attempt to re-enable the retired “less secure apps” setting. Google recommends modern account sign-in where supported. An eligible account can use an app password for software that cannot use that flow. This is not a claim that app passwords were newly invented in 2022. Google’s less-secure-app guidance.
Two-Factor Authentication
Google app passwords require 2-Step Verification. The original advice to skip that requirement, or create an app password without enabling it, was incorrect.
Availability also depends on account policy. Organization-managed accounts, Advanced Protection and some security-key-only configurations may not offer the option. If it is unavailable, use a supported authentication arrangement rather than substituting your ordinary password. Google app-password requirements.
What if My Gmail Uses 2-Factor Authentication?
An app password lets compatible software authenticate without an interactive second-factor prompt on each connection. It is still a credential with access to the account; an application label is not proof of narrowly restricted mailbox permissions. Give the installation a distinct label so its credential can be revoked independently.
Google says changing the account password revokes app passwords. Revocation or policy changes can therefore interrupt alert delivery; monitor failures instead of assuming the configuration will work indefinitely. App-password behavior.
How to Create an Application-Specific Password for Gmail
Follow the current steps in Google’s app-password help:
- Sign in to the intended account and confirm that 2-Step Verification and account policy permit app passwords.
- Open the account’s App passwords settings and create a clearly named credential for the host/application.
- Enter it directly into the protected credential file described below. Avoid placing it in shell commands/history, screenshots, shared notes or source control.
- Revoke it when the installation is retired. If it is lost, create a replacement; the generated secret is only shown once.
Google’s interface changes over time. “Manage third-party access” concerns connected-app permissions and is not the same operation as generating an app password.
Historical account-interface screenshots from the original article
These images document the older interface. They are not a current click-by-click procedure; the third-party-access screen is a separate account feature.
Configure Postfix
The following example assumes a dedicated host submitting local alerts, not a mail server accepting mail from other machines. Back up its current Postfix configuration with a unique filename before adapting it.
First check which indexed map types are available:
postconf -m
The example uses hash:. Confirm hash appears in that output; if it does not, use an installed backend consistently in both postmap and smtp_sasl_password_maps, following its file/permission rules. Do not assume every future distribution has the same default database backend.
Create or secure the credential file before entering a secret. These commands do not truncate an existing file:
sudo install -d -o root -g root -m 0700 /etc/postfix/sasl
sudo touch /etc/postfix/sasl/sasl_passwd
sudo chown root:root /etc/postfix/sasl/sasl_passwd
sudo chmod 0600 /etc/postfix/sasl/sasl_passwd
sudo nano /etc/postfix/sasl/sasl_passwd
Use this record format, replacing both placeholders in the editor:
[smtp.gmail.com]:587 your_account@gmail.com:YOUR_APP_PASSWORD
The destination key must exactly match the relay’s brackets and port. For the hash: example, build and protect the indexed map:
sudo sh -c 'umask 077; postmap hash:/etc/postfix/sasl/sasl_passwd'
sudo chown root:root /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db
sudo chmod 0600 /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db
Both files contain usable credentials. postmap creates a lookup database, not a one-way password hash or encrypted secret store. Regenerate the database after changing the text file. postmap documentation.
Edit /etc/postfix/main.cf. Update existing parameters rather than appending conflicting duplicates. Their location relative to mydestination or mynetworks is not significant:
# Dedicated local-submission host: no public SMTP listener.
inet_interfaces = loopback-only
mydestination =
relayhost = [smtp.gmail.com]:587
# SMTP client authentication to Gmail.
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous
# STARTTLS, trusted certificate chain, and configured relay-name match.
smtp_tls_wrappermode = no
smtp_tls_security_level = secure
smtp_tls_secure_cert_match = nexthop
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
inet_interfaces = loopback-only limits the listener to this host, while an empty mydestination implements the no-local-delivery model. This changes where local mail goes, so arrange valid recipients and senders for system-generated messages as well as your script. The example’s explicit envelope sender and From header should use the authenticated Gmail address or a permitted verified alias. Postfix null-client configuration.
The original encrypt TLS level required encryption but did not require a trusted certificate or matching server identity. secure with nexthop verifies the configured relay hostname. Keep the CA bundle current; fix certificate, hostname or clock problems instead of disabling verification. Postfix TLS security levels.
Check the configuration, then restart because listener-address changes require it:
sudo postfix check
sudo systemctl restart postfix
sudo systemctl status postfix --no-pager
A successful service start does not prove SMTP authentication or delivery. No actual credential or remote account is modified by this article review.
Test Server Email Sending Capability
After configuring the actual host, send one clearly labeled message to an inbox you control. The examples below are instructions for that test; they were not sent during this local review.
Check the submission exit status, Postfix queue and delivery logs, and then confirm receipt in the inbox (including spam). A zero exit code normally indicates acceptance for processing, not guaranteed final delivery. “Sent” in a relay log can mean the next server accepted it, not that it reached the inbox.
postqueue -p
sudo journalctl --since '10 minutes ago' --no-pager | grep -i postfix
Depending on logging configuration, Postfix events may instead be in /var/log/mail.log. Look for the queue ID and distinguish deferred, bounced and handed-off messages. Avoid repeatedly submitting tests when an earlier message is still queued.
Method 1: Piping the Whole Enchilada
Postfix’s sendmail -t extracts recipients from message headers. -f sets the envelope sender separately, and -i prevents a lone period in the body from prematurely ending input. Replace the sender and recipient placeholders before running:
printf '%s\n' \
'From: Server Alerts <your_account@gmail.com>' \
'To: your_inbox@example.net' \
'Subject: [TEST] Ubuntu Gmail relay' \
'MIME-Version: 1.0' \
'Content-Type: text/plain; charset=UTF-8' \
'' \
'This is a clearly labeled test of the Ubuntu Gmail relay.' \
| /usr/sbin/sendmail -i -t -f your_account@gmail.com
The empty string creates the required blank line between headers and body. A display name alone is not a complete From mailbox. For arbitrary or untrusted content, use a mail library that encodes headers and prevents header injection rather than concatenating unvalidated strings. Postfix submission interface.
Method 2: Email the Contents of a File
Create message.txt with actual sender/recipient addresses. The blank line is required; a trailing lone period is not required when the file ends at EOF:
From: Server Alerts <your_account@gmail.com>
To: your_inbox@example.net
Subject: [TEST] Ubuntu Gmail relay from file
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
This is a test message read from a file.
Submit it with:
/usr/sbin/sendmail -i -t -f your_account@gmail.com < message.txt
With -i, a period-only line is ordinary body content. -t obtains recipients from the headers; alternatively, recipients can be supplied as command arguments. Header addresses and the envelope sender have separate roles. Internet message format.
Nerd Facts
HTML email needs an appropriate MIME content type, such as text/html; charset=UTF-8, and correct encoding; putting HTML tags in an otherwise plain-text body is not enough. Rendering depends on the mail client, not merely whether it runs in a browser. A multipart message with a plain-text alternative is useful when HTML is necessary. MIME specification.
Use the documentation for Postfix’s Sendmail-compatible interface installed on this host. The original Sendmail 8.17.1 release and 8.12 documentation references concern a different mail-transfer-agent implementation, not this Postfix package.