How to Send an email from AWS ec2 or Azure VM or Google Instance using mail or sendmail linux commands

Posted by

Sending an email directly from cloud virtual machines (VMs) like AWS EC2, Azure VM, or Google Cloud Compute Engine using command-line tools such as mail or sendmail can be a straightforward task, but it does require some initial setup and consideration of the cloud provider’s policies and limitations. Here’s a general guide on how to set up and send an email using these commands on a cloud VM:

General Steps for Setup

  1. Install Mail Utilities: Depending on the Linux distribution, you might need to install mail utilities. Common utilities include mailx, sendmail, or postfix.
For Ubuntu/Debian systems:

$ sudo apt update
$ sudo apt install mailutils

For RedHat/CentOS systems:

$ sudo yum update
$ sudo yum install mailx
  1. Configure SMTP: To send emails, you need to configure an SMTP server. You can use your cloud provider’s email service (like Amazon SES, Google’s SMTP relay, or SendGrid) or any external SMTP service.
  2. Edit Configuration Files: If using sendmail or postfix, you’ll need to configure them to send emails via your chosen SMTP server. This typically involves editing /etc/postfix/main.cf or similar files to set up SMTP relay settings.

Using AWS SES, Google SMTP, or SendGrid

For simplicity, here’s how you could configure using an external SMTP like AWS SES:

  1. Configure SMTP Settings: Modify your postfix configuration to use AWS SES:
sudo postconf -e 'relayhost = [email-ses-region.amazonaws.com]:587'
sudo postconf -e 'smtp_sasl_auth_enable = yes'
sudo postconf -e 'smtp_sasl_security_options = noanonymous'
sudo postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
sudo postconf -e 'smtp_use_tls = yes'
sudo postconf -e 'smtp_tls_security_level = encrypt'
sudo postconf -e 'smtp_tls_note_starttls_offer = yes'
  1. Replace email-ses-region.amazonaws.com with the appropriate endpoint for your SES instance.
  2. Create SASL Password File: You need to create a file to store your SES credentials.
sudo sh -c 'echo "[email-ses-region.amazonaws.com]:587 USERNAME:PASSWORD" > /etc/postfix/sasl_passwd'
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd
  1. Replace USERNAME and PASSWORD with your SES SMTP credentials.
  2. Reload/Restart Postfix:
sudo systemctl restart postfix

Send an Email

After configuration, you can send an email using the mail command:

echo "This is the body of the email" | mail -s "Subject Here" user@example.com

Leave a Reply

Your email address will not be published. Required fields are marked *