auahmed
auahmed

Reputation: 151

Send mail through bash script

Hey I was just wondering when I trying to create a bash script which can send mail. To start off I was testing mail out using the command line but when I run the command nothing happens. I suppose the command tries to send it but it never goes through and it just hangs and I have to send the kill letter.

These are the commands i have tried:

mail -s "Subject" [email protected]
mailx -s "Subject" [email protected]

Upvotes: 1

Views: 1776

Answers (2)

David W.
David W.

Reputation: 107040

First, you need to send a message with your mail. We can also try verbose mode:

$ mailx -v -s "Test Message" [email protected] <<EOM
> This is my message I want to send.
> I can keep typing it and the last line ends with just "EOM"like this:
> EOM
Mail Delivery Status Report will be mailed to <foo>.
$

The <<EOM is called a Here Document. It tells your computer to expect input to direct to the command from STDIN (the keyboard), and that the input will end with the string that followed the << characters (here EOM).

You'll get a mail report emailed to you. You can use mailx to read it, or one of those fancy new email programs like elm or pine, or just read your mail from the command line via mailx:

$ mailx
Mail version 8.1 6/6/93.  Type ? for help.
"/var/mail/foo": 1 message 1 new
>N  1 MAILER-DAEMON@davebo  Mon Nov 24 14:04  67/2465  "Mail Delivery Status Report"
? s
No file specified: using MBOX.
"/home/users/foo/mbox" [New file]
? q
$

Now, you should have a file called mbox in your $HOME directory. Take a look at this file, and see what it says. I got this:

$ vi $HOME/mbox

Enclosed is the mail delivery report that you requested.

                   The mail system

<[email protected]>: delivery via
    mail.foo.com[XX.XX.XX.XX]:25: host
    mail.foo.com[XX.XX.XX.XX] refused to talk to me: 554
     -Please submit an unblock request 
    <http://x.co/rblbounce>

Looks like I'm blocked.

Upvotes: 1

Micah Smith
Micah Smith

Reputation: 4463

With the syntax you use, mail is certainly waiting for you to type a message on standard input, as suggested in the comments. You could:

--type a message yourself after the command, terminating with a C-d

--Use syntax like this to write a string to the body:

mail -s "Subject" [email protected] <<< "Hello"

--Different syntax

echo "Hello" | mail -s "Subject" [email protected]

Especially if you are going to be sending mail in a script, you would want to consider either of the last two approaches.

Upvotes: 0

Related Questions