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
- Install Mail Utilities: Depending on the Linux distribution, you might need to install mail utilities. Common utilities include
mailx
,sendmail
, orpostfix
.
For Ubuntu/Debian systems:
$ sudo apt update
$ sudo apt install mailutils
For RedHat/CentOS systems:
$ sudo yum update
$ sudo yum install mailx
- 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.
- Edit Configuration Files: If using
sendmail
orpostfix
, 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:
- 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'
- Replace
email-ses-region.amazonaws.com
with the appropriate endpoint for your SES instance. - 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
- Replace
USERNAME
andPASSWORD
with your SES SMTP credentials. - 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