The Approach
Step 1: Obtain the SMTP Gmail server details. Here we will be sending the email through the Gmail SMTP server. For this we might need to obtain the Gmail SMTP server details, which includes the following.
- You will need your Gmail email address, which serves as your sender’s email address. If you don’t have a Gmail account, you can create one for free at https://mail.google.com/.
- You’ll need the password for your Gmail account. If you have two-factor authentication (2FA) enabled for your Gmail account, you should use an “App Password” instead of your regular Gmail password. You can use this link https://myaccount.google.com/apppasswords to generate an app password for your account.
NOTE: Regular Gmail password for SMTP authentication is not recommended if you have two-factor authentication (2FA) enabled. Generating and using an App Password is a more secure way to authenticate your email client or script when sending emails through Gmail’s SMTP server.
Step 2: Create a bash script using the following command, and open the file using a text editor of your choice.
$ touch email.sh
Step 3: Use the below shell script.
#!/bin/bash
# SMTP server settings for Gmail
SMTP_SERVER="smtp.gmail.com"
SMTP_PORT="587"
SMTP_USERNAME="YOUR_GMAIL_ADDRESS"
SMTP_PASSWORD="YOUR_GMAIL_PASSWORD"
# Recipient email address
TO="RECIPIENT_EMAIL_ADDRESS"
# Email subject and body
SUBJECT="Hello from Curl"
BODY="This is the email body sent using Curl and SMTP."
# Construct the email message
MESSAGE="Subject: $SUBJECT\n\n$BODY"
# Send the email using Curl
curl --url "smtp://$SMTP_SERVER:$SMTP_PORT" \
--ssl-reqd \
--mail-from "$SMTP_USERNAME" \
--mail-rcpt "$TO" \
--user "$SMTP_USERNAME:$SMTP_PASSWORD" \
--tlsv1.2 \
-T <(echo -e "$MESSAGE")
echo "Email sent to $TO"
Step 3: Modify the permissions to executable and then run the script.
chmod +x ./email.sh
Step 4: Execute the script using the following command
./email.sh
Using curl to send email
In this article, we shall see how to harness the power of the “curl” command line tool and Gmail SMTP server in order to send an email programmatically using a bash script, “curl” is a versatile and powerful utility command line tool for making HTTP requests. And is primarily known for transferring data from and to servers using various kinds of protocols such as HTTP, HTTPS, FTP, FTPS, and SCP. “curl” is an open-source tool and is available on various unix-based systems such as Linux and macOS. It is also available for the Windows operating system as well.