Sending Mail Through Gmail's SMTP Server with msmtp

How to Configure Gmail SMTP in msmtp

* This page contains promotional content

I want to install msmtp on Debian10 and send mail through Gmail’s SMTP server

msmtp

On hosts that only send mail I used to use sSMTP a lot, but on Debian10 there is no ssmtp package.
The replacement for it is msmtp

Installing msmtp

# apt install msmtp msmtp-mta

Configuration

There is no configuration file in /etc, so copy the sample

# cp /usr/share/doc/msmtp/examples/msmtprc-system.example /etc/msmtprc

Incidentally, for a per-user configuration it is

# cp /usr/share/doc/msmtp/examples/msmtprc-user.example ~/.msmtprc

Editing the configuration file

# Set default values for all following accounts.
defaults
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# gmail service
account gmail
host smtp.gmail.com
port 587
from [email protected]
user [email protected]
password ******

# Set a default account
account default : gmail

Send test

$ echo "hello world." | msmtp [email protected]
msmtp: account default not found: no configuration file available

There is nothing wrong with the configuration file, so in this case it is a permissions problem

# chown root:msmtp /etc/msmtprc
# chmod 640 /etc/msmtprc

Apart from that, if the error below appears, set the host field in msmtprc to an IP

msmtp: account default from /etc/msmtprc: host not set

Trying to send again, a gmail send error

$ echo "hello world." | msmtp [email protected]
msmtp: authentication failed (method PLAIN)
msmtp: server message: 534-5.7.9 Application-specific password required. Learn more at
msmtp: server message: 534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor c130sm1091555pfc.51 - gsmtp
msmtp: could not send mail (account default from /etc/msmtprc)

When two-step verification is enabled, it turns out you have to set an application-specific password to access the Google account (Application-specific password required)

If you do not have two-step verification enabled, sending should have succeeded at this point. (In that case the following is unnecessary.)

Generating an app password

An app password lets you sign in to your Google account from an app on a device that does not support two-step verification. You only have to enter this password once; after that you do not need to remember it.

Click the app password field, and under デバイス選択 choose その他 and enter any name you like

When you finally press generate, a code is issued, so save it (the generated code is different for everyone)

rxgvdegplcmoxxxx

Replace the password in msmtprc with this code
(the password is not the user’s login password but this code)

If no error appears when sending and the mail arrives, you have succeeded

See also