How to Send Gmail Email With Postfix on Ubuntu

In this guide, we will walk you through the steps to configure Postfix on an Ubuntu system to send emails through your Gmail account. This can be useful for various purposes, such as sending automated emails from your server. Follow these steps:

Step 1: Install Required Packages

First, you need to install the necessary packages. Open a terminal and run the following command:

1
2
sudo apt update
sudo apt install postfix libsasl2-modules mailutils

During the installation process, you will be prompted to configure Postfix. Select “Internet Site” and press Enter. Enter your domain name (or set your localhost name if you don’t have a domain).

Step 2: Create the SASL Password File

Now, you need to create a file to store your Gmail account credentials securely. Open the SASL password file for editing with your preferred text editor. In this example, we’ll use Vim:

1
sudo vim /etc/postfix/sasl/sasl_passwd

Add the following line to the file, replacing [email protected] with your Gmail email address and password with your Gmail password:

1
[smtp.gmail.com]:587 [email protected]:password

Save and close the file.

Next, restrict the permissions of this file to ensure it’s not accessible to unauthorized users:

1
sudo chmod 0600 /etc/postfix/sasl/sasl_passwd

Then, create a hash database from this file:

1
sudo postmap /etc/postfix/sasl/sasl_passwd

Step 3: Configure Postfix

Open the Postfix configuration file for editing:

1
sudo vim /etc/postfix/main.cf

Find the line that starts with relayhost = and modify it as follows:

1
relayhost = [smtp.gmail.com]:587

Add the following lines to enable SASL authentication, disallow anonymous authentication, specify the location of the SASL password file, enable STARTTLS encryption, and specify the location of CA certificates:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Enable SASL authentication
smtp_sasl_auth_enable = yes

# Disallow methods that allow anonymous authentication
smtp_sasl_security_options = noanonymous

# Location of sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd

# Enable STARTTLS encryption
smtp_tls_security_level = encrypt

# Location of CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Save and close the file.

Step 4: Restart Postfix

To apply the changes you made to the Postfix configuration, restart the Postfix service:

1
sudo systemctl restart postfix

Sending Gmail Emails with Postfix

You have now configured Postfix to send emails through your Gmail account. You can use the mail command or any other email-sending application on your Ubuntu server to send emails via your Gmail account through the Postfix configuration you set up.

Remember to use this configuration responsibly, and do not share your Gmail credentials or leave them exposed on your server.

0%