Skip to content

Instantly share code, notes, and snippets.

@justkelvin
Forked from movd/emails_from_ubuntu.md
Created January 21, 2023 14:03
Show Gist options
  • Save justkelvin/7639665e37fd5a5398c72d7e96e8cb81 to your computer and use it in GitHub Desktop.
Save justkelvin/7639665e37fd5a5398c72d7e96e8cb81 to your computer and use it in GitHub Desktop.
Set up msmtp to send emails emails from Ubuntu/Debian Servers

Setting up email with SMTP on Ubuntu/Debian Servers

I used to sift trough my shell history and bookmarks every time I set up a new testing server in order to be able to send mails. So this should help...

Be aware don't use ssmtp anymore. It's unmaintained and has been removed from Debian and Ubuntu will most definitely follow suit.

Install msmtp

First we need the awesome program called msmtp to route all the server's mail through a standard SMTP server.

sudo apt-get install msmtp msmtp-mta mailutils

Set up msmtp

sudo nano /etc/msmtprc

# Set default values for all following accounts.
defaults

# Use the mail submission port 587 instead of the SMTP port 25.
port 587

# Always use TLS.
tls on

# Set a list of trusted CAs for TLS. The default is to use system settings, but
# you can select your own file.
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# The SMTP server of your ISP
account isp
host mail.isp.example
from smithjoe@isp.example
auth on
user 12345

# Set default account to isp
account default: isp

# Map local users to mail addresses
aliases /etc/aliases

The above is based on the example. The program has many more authentication methods.

Install and set up mailx

In order to be able to use the mail command wee need to install mailx

sudo apt-get install bsd-mailx

Set mail transport agent to use msmtp

sudo nano /etc/mail.rc

append the following:

set mta=/usr/bin/msmtp

Set up aliases

We need to link system users with email addresses in order for system users to receive mails from cronjobs.

sudo nano /etc/aliases

# Send root to Jane
root: jane_doe@example.com
   
# Send everything else to admin
default: admin@domain.example

sudo nano /etc/mail.rc

append:

alias root root<jane_doe@example.com>

Emails are now sent to this address if e.g. a cronjob fails. Also a general fallback address is used if messages don't belong to root. Of course more users can be set.

Test it!

echo "Hello World" | msmtp -d bob@example.com

Test sending a mail to root

echo "Testing msmtp from ${HOSTNAME} with mail command" | mail -s "hi root" root

Test sending a mail to another email adress

echo "Testing msmtp from ${HOSTNAME} with mail command" | mail -s "hi there" bob@example.com

Links

https://marlam.de/msmtp/

https://wiki.archlinux.org/index.php/Msmtp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment