Sending Mail from a Linux Environment

CJ writes
3 min readSep 20, 2023

--

In this blog post, we will explore how to send emails from a Linux environment. For this example, I’m using the Ubuntu flavor, and we’ll be utilizing msmtp to send our emails.

msmtp is a lightweight command-line SMTP client that simplifies sending email directly from the terminal or shell scripts. It’s a versatile tool known for its efficiency and ease of use in Linux-based environments

Let’s begin with the installation and setup :

sudo apt-get install msmtp

Create the msmtp configuration file

touch ~/.msmtprc
chmod 600 ~/.msmtprc
vi ~/.msmtprc
chmod +x ~/.msmtprc

Inside ~/.msmtprc, add the following configuration:

auth on
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile ~/.msmtp.log

account default
host smtp.gmail.com
port 587
auth on
from your_mail@gmail.com
user your_mail@gmail.com
password "Generate a app password and pass it here for Auth, dont use your mail password directly"

Note : Please use Google App passwords for authentication. You can find more information at this link https://support.google.com/accounts/answer/185833?hl=en#

Now, let’s create a script to send emails :

vi mail-script.sh

Paste the following code into mail-script.sh:

#!/bin/bash

read -p "Enter recipient email address: " recipient

subject="HTML Email Example"

html_file="/tmp/email.html"

html_content="<html>
<head></head>
<body>
<h1>Hello, This is an HTML email!</h1>
<b style="color:pink">This is the body of the email.</b>
</body>
</html>"

# Write the HTML content to the temporary file
echo "$html_content" > "$html_file"

# Use msmtp to send the email with subject and recipient
if [ -f "$html_file" ]; then
msmtp -t <<EOF
To: $recipient
Subject: $subject
Content-Type: text/html

$(cat "$html_file")
EOF
echo "Mail Sent Successfully"
else
echo "HTML file not found: $html_file"
fi

Save and exit the script file.

To run the script and send an email, use one of the following commands

./mail-script.sh or sh mail-script.sh

The script will prompt you to enter the recipient’s email address, and then it will send the HTML content to the specified recipient.

Verify it from your Gmail account

Additionally, if you want to send mail from a Windows environment, you can obviously use Gmail or Outlook directly. However, if you prefer to use the command line interface (CLI), you can try this command

Send-MailMessage -SmtpServer 'smtp.gmail.com' -Port 587 -UseSsl -From 'your_mail@gmail.com' -To 'your_mail@gmail.com' -Subject 'Subject' -Body 'Email body' -Credential 'passwd'

This command allows you to send an email from a Windows environment using PowerShell.

That’s it. Thanks for reading. Lots of love to you❤️

--

--

CJ writes

Tech explorer passionate about #DevOps, ☁️ #Cloud, 🤖 #AI. Join me as we decode tech trends and discuss global incidents! 🌐