Sending a mail from a linux shell script
Asked Answered
W

12

142

I want to send an email from a Linux Shell script. What is the standard command to do this and do I need to set up any special server names?

Whisper answered 1/3, 2011 at 14:36 Comment(2)
Try asking on Superuser [superuser.com ] or, better yet, Unix and Linux SE [unix.stackexchange.com ].Schistosome
Possible duplicate of Shell script to send emailLists
M
131

If the server is well configured, eg it has an up and running MTA, you can just use the mail command.

For instance, to send the content of a file, you can do this:

$ cat /path/to/file | mail -s "your subject" [email protected]

man mail for more details.

Mellicent answered 1/3, 2011 at 14:51 Comment(4)
What does 'mta' mean here, is there a full name or a link? As a beginner, that's what I want to know. As I lack of experience to do that.Oudh
@Oudh MTA stands for Mail transport agent. postfix, sendmail, qmail etcMellicent
@Oudh for the most part, you can consider MTA to mean SMTP or IMAP server.Upsurge
If you're not sure how to install/configure and you're on Ubuntu: sudo apt-get install mailutils and select Internet site: Mail is sent and received directly using SMTP..Engler
W
94

If you want a clean and simple approach in bash, and you don't want to use cat, echo, etc., the simplest way would be:

mail -s "subject here" [email protected] <<< "message"

<<< is used to redirect standard input. It's been a part of bash for a long time.

Waterscape answered 19/11, 2012 at 4:58 Comment(4)
echo -e "Some\nMultiline and tab\t msg"|mail -s "subject" [email protected]Wharfage
cat << END ... END | mail -s "subject" [email protected]Brimful
Hey, this worked great for me, thanks! How would I specify multiple addresses to deliver to?Scibert
@Scibert You can use the -t option to send to multiple addresses separated by spacesCostmary
H
29

If both exim and ssmtp are running, you may enter into troubles. So if you just want to run a simple MTA, just to have a simple smtp client to send email notifications for insistance, you shall purge the eventually preinstalled MTA like exim or postfix first and reinstall ssmtp.

Then it's quite straight forward, configuring only 2 files (revaliases and ssmtp.conf) - See ssmtp doc - , and usage in your bash or bourne script is like :

#!/bin/sh  
SUBJECT=$1  
RECEIVER=$2  
TEXT=$3  

SERVER_NAME=$HOSTNAME  
SENDER=$(whoami)  
USER="noreply"

[[ -z $1 ]] && SUBJECT="Notification from $SENDER on server $SERVER_NAME"  
[[ -z $2 ]] && RECEIVER="another_configured_email_address"   
[[ -z $3 ]] && TEXT="no text content"  

MAIL_TXT="Subject: $SUBJECT\nFrom: $SENDER\nTo: $RECEIVER\n\n$TEXT"  
echo -e $MAIL_TXT | sendmail -t  
exit $?  

Obviously do not forget to open your firewall output to the smtp port (25).

Hauger answered 2/3, 2011 at 17:53 Comment(5)
Where can I change the port number in this script? In my server smtp port works over 8181.Bidarka
I would not do this in this shell otherwise you will get stucked sooner or later. You might do it in the config file : See unix.stackexchange.com/a/132731Hauger
Why are newlines being ingored if I make simple echo $MAIL_TXT?Almoner
@Marko : Pls see man echo with -e option : enable interpretation of backslash escapesHauger
Sorry, did mis the -e parameterAlmoner
D
10

Another option for in a bash script:

mailbody="Testmail via bash script"
echo "From: [email protected]" > /tmp/mailtest
echo "To: [email protected]" >> /tmp/mailtest
echo "Subject: Mailtest subject" >> /tmp/mailtest
echo "" >> /tmp/mailtest
echo $mailbody >> /tmp/mailtest
cat /tmp/mailtest | /usr/sbin/sendmail -t
  • The file /tmp/mailtest is overwritten everytime this script is used.
  • The location of sendmail may differ per system.
  • When using this in a cron script, you have to use the absolute path for the sendmail command.
Deidradeidre answered 10/11, 2015 at 13:12 Comment(2)
downvoted because more than one process could call the script at the same time. This could cause corrupt/incorrect tmp file. Also the /tmp file is not overwritten each time this is used - it actually grows with each email containing all previous emails inside. Not good.Decor
The first write to /tmp/mailtest is an overwrite so it will remove whatever was in there previously. Still, this method is not ideal for the other reasons you have described.Insufferable
S
10

SEND MAIL FROM LINUX TO GMAIL

USING POSTFIX

1: install software

Debian and Ubuntu:

apt-get update && apt-get install postfix mailutils

OpenSUSE:

zypper update && zypper install postfix mailx cyrus-sasl

Fedora:

dnf update && dnf install postfix mailx

CentOS:

yum update && yum install postfix mailx cyrus-sasl cyrus-sasl-plain

Arch Linux:

pacman -Sy postfix mailutils

FreeBSD:

portsnap fetch extract update

cd /usr/ports/mail/postfix

make config

in configaration select SASL support

make install clean

pkg install mailx

2. Configure Gmail

/etc/postfix. Create or edit the password file:

vim /etc/postfix/sasl_passwd

i m using vim u can use any file editer like nano, cat .....

>Ubuntu, Fedora, CentOS,Debian, OpenSUSE, Arch Linux:

add this

where user replace with your mailname and password is your gmail password

[smtp.gmail.com]:587    [email protected]:password

Save and close the file and Make it accessible only by root: becouse its an sensitive content which contains ur password

chmod 600 /usr/local/etc/postfix/sasl_passwd

>FreeBSD:

directory /usr/local/etc/postfix.

vim /usr/local/etc/postfix/sasl_passwd

Add the line:

[smtp.gmail.com]:587    [email protected]:password

Save and Make it accessible only by root:

chmod 600 /usr/local/etc/postfix/sasl_passwd

3. Postfix configuration

configuration file main.cf

6 parameters we must set in the Postfix

Ubuntu, Arch Linux,Debian:

edit

 vim /etc/postfix/main.cf

modify the following values:

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

smtp_sasl_security_options which in configuration will be set to empty, to ensure that no Gmail-incompatible security options are used.

save and close

as like for

OpenSUSE:

vim /etc/postfix/main.cf

modify

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/ca-bundle.pem

it also requires configuration of file master.cf

modify:

vim /etc/postfix/master.cf

as by uncommenting this line(remove #)

#tlsmgr unix - - n 1000? 1 tlsmg

save and close

Fedora, CentOS:

vim /etc/postfix/main.cf

modify

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt

FreeBSD:

vim /usr/local/etc/postfix/main.cf

modify:

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options =
smtp_sasl_password_maps = hash:/usr/local/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/mail/certs/cacert.pem

save and close this

4. Process Password File:

Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:

postmap /etc/postfix/sasl_passwd

for freeBSD

postmap /usr/local/etc/postfix/sasl_passwd

4.1) Restart postfix

Ubuntu, Fedora, CentOS, OpenSUSE, Arch Linux,Debian:

systemctl restart postfix.service

for FreeBSD:

service postfix onestart
nano /etc/rc.conf

add

postfix_enable=YES

save then run to start

service postfix start

5. Enable "Less Secure Apps" In Gmail using help of below link

https://support.google.com/accounts/answer/6010255

6. Send A Test Email

mail -s "subject" [email protected]

press enter

add body of mail as your wish press enter then press ctrl+d for proper termination

if it not working check the all steps again and check if u enable "less secure app" in your gmail

then restart postfix if u modify anything in that

for shell script create the .sh file and add 6 step command as your requirement

for example just for a sample

#!/bin/bash
REALVALUE=$(df / | grep / | awk '{ print $5}' | sed 's/%//g')
THRESHOLD=80

if [ "$REALVALUE" -gt "$THRESHOLD" ] ; then
    mail -s 'Disk Space Alert' [email protected] << EOF
Your root partition remaining free space is critically low. Used: $REALVALUE%
EOF
fi

The script sends an email when the disk usage rises above the percentage specified by the THRESHOLD varialbe (80% here).

Seligman answered 26/10, 2019 at 17:42 Comment(1)
Shouldn't the name of this answer should be "SEND MAIL FROM LINUX TO [email protected] VIA GMAIL"?Lohse
U
9

Generally, you'd want to use mail command to send your message using local MTA (that will either deliver it using SMTP to the destination or just forward it into some more powerful SMTP server, for example, at your ISP). If you don't have a local MTA (although it's a bit unusual for a UNIX-like system to omit one), you can either use some minimalistic MTA like ssmtp.

ssmtp is quite easy to configure. Basically, you'll just need to specify where your provider's SMTP server is:

# The place where the mail goes. The actual machine name is required
# no MX records are consulted. Commonly mailhosts are named mail.domain.com
# The example will fit if you are in domain.com and you mailhub is so named.
mailhub=mail

Another option is to use one of myriads scripts that just connect to SMTP server directly and try to post a message there, such as Smtp-Auth-Email-Script, smtp-cli, SendEmail, etc.

Unbreathed answered 1/3, 2011 at 16:4 Comment(1)
"ssmtp" was is installed on the machine so I was unable to try it but thanks anywayWhisper
S
6

Admitting you want to use some smtp server, you can do:

export SUBJECT=some_subject
export smtp=somehost:someport
export EMAIL=someaccount@somedomain
echo "some message" | mailx -s "$SUBJECT" "$EMAIL"

Change somehost, someport, and someaccount@somedomain to actual values that you would use. No encryption and no authentication is performed in this example.

Slat answered 11/10, 2012 at 16:22 Comment(1)
And what to do if mailx is not installed?Beffrey
H
3

you can use 'email' or 'emailx' command.

(1) $ vim /etc/mail.rc # or # vim /etc/nail.rc


set from = [email protected] #
set smtp = smtp.exmail.gmail.com #gmail's smtp server 
set smtp-auth-user = [email protected] #sender's email address
set smtp-auth-password = xxxxxxx #get from gmail, not your email account passwd
set smtp-auth=login #because if it is not sent from an authorized account, email will get to junk mail list.

(2)

$ echo "Pls remember to remove unused ons topics!" | mail -s "waste topics" -a a.txt [email protected] #send to group user '[email protected]' 
Hard answered 1/4, 2019 at 4:24 Comment(0)
R
2

The mail command does that (who would have guessed ;-). Open your shell and enter man mail to get the manual page for the mail command for all the options available.

Rhodian answered 1/3, 2011 at 14:40 Comment(2)
I did that but there is no option to specify a server to useWhisper
That is part of your local mail transfer agent configuration, e.g. Sendmail or Postfix.Rhodian
H
2

You don't even need an MTA. The SMTP protocol is simple enough to directly write it to your SMTP server. You can even communicate over SSL/TLS if you have the OpenSSL package installed. Check this post: https://33hops.com/send-email-from-bash-shell.html

The above is an example on how to send text/html e-mails that will work out of the box. If you want to add attachments the thing can get a bit more complicated, you will need to base64 encode the binary files and embed them between boundaries. THis is a good place to start investigating: http://forums.codeguru.com/showthread.php?418377-Send-Email-w-attachments-using-SMTP

Harrietharriett answered 12/7, 2016 at 19:3 Comment(0)
A
2

On linux, mail utility can be used to send attachment with option "-a". Go through man pages to read about the option. For eg following code will send an attachment :

mail -s "THIS IS SUBJECT" -a attachment.txt [email protected] <<< "Hi Buddy, Please find failure reports."

Arnelle answered 21/2, 2018 at 11:22 Comment(1)
Welcome to SO. Thanks for posting an answer. Please read the info about how to write a good answer and modify accordingly. Enjoy SO ;-)Thrawn
P
1

Alternative way to send email with large text body from a file:

mail -s "[subject]" -a attachment [recipient] < [file_path], e.g.

mail -s "your subject" -a /path/to/attachment [email protected] < /path/to/mail_body.txt

Note: mail in mailx utility uses -a for attachment, mail in mailutils package uses -A for attachment

Preestablish answered 19/4 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.