ridogi
ridogi

Reputation: 451

Sending mail from a Bash shell script

I am writing a Bash shell script for Mac that sends an email notification by opening an automator application that sends email out with the default mail account in Mail.app. The automator application also attaches a text file that the script has written to. The problems with this solution are

  1. It is visible in the GUI when sending
  2. It steals focus if Mail is not the current application
  3. It is dependent on Mail.app's account setup being valid in the future

I figure to get around those shortcomings I should send the mail directly from the script by entering SMTP settings, address to send to, etc. directly in the script. The catch is I would like to deploy this script on multiple computers (10.5 and 10.6) without enabling Postfix on the computer. Is it possible to do this in the script so it will run on a base Mac OS X install of 10.5. and 10.6?

Update: I've found the -bs option for Sendmail which seems to be what I need, but I'm at a loss of how to specify settings.

Also, to clarify, the reason I'd like to specify SMTP settings is that mails from localhost on port 25 sent out via Postfix would be blocked by most corporate firewalls, but if I specify the server and an alternate port I won't run into that problem.

Upvotes: 39

Views: 92167

Answers (12)

Jason R. Coombs
Jason R. Coombs

Reputation: 42639

Previously, this answer was based on the default inclusion of a recent Python on Mac OS X. Since then, the Python ecosystem has evolved and Python is not available on a clean install. This answer has been updated for modern systems, but is much more involved and exceeds the scope of the original poster's request.

Python and it's built-in standard library provides some nice facilities for sending email if you're willing to install it. Consider using the stock installer or installing homebrew followed by brew install python.

From there, customize the following script based on stock examples to suit your needs.

# Settings

SMTP_SERVER = 'mail.myisp.com'
SMTP_PORT = 25
SMTP_USERNAME = 'myusername'
SMTP_PASSWORD = '$uper$ecret'
SMTP_FROM = '[email protected]'
SMTP_TO = '[email protected]'

TEXT_FILENAME = '/script/output/my_attachment.txt'
MESSAGE = """This is the message
to be sent to the client.
"""

# Now construct the message
import pathlib
import smtplib
import email.message

msg = email.message.EmailMessage()
msg.set_content(MESSAGE)
text_path = pathlib.Path(TEXT_FILENAME)
msg.add_attachment(
    text_path.read_text(),
    maintype='text',
    subtype='plain',
    filename=text_path.name,
)
msg['From'] = SMTP_FROM
msg['To'] = SMTP_TO
# msg['Subject'] = SMTP_SUBJECT

# Now send the message
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as mailer:
    mailer.login(SMTP_USERNAME, SMTP_PASSWORD)
    mailer.send_message(msg)

I hope this helps.

Upvotes: 56

motobói
motobói

Reputation: 1805

Try mtcmail. Its a fairly complete email sender, completely standalone.

Upvotes: 0

Mark Carey
Mark Carey

Reputation: 1587

sendEmail is a script that you can use to send email from the command line using more complicated settings, including connecting to a remote smtp server: http://caspian.dotconf.net/menu/Software/SendEmail/

On OSX it is easily installable via macports: http://sendemail.darwinports.com/

Below is the help page for the command, take note of the -s, -xu, -xp flags:

Synopsis:  sendEmail -f ADDRESS [options]

Required:
  -f ADDRESS                from (sender) email address
  * At least one recipient required via -t, -cc, or -bcc
  * Message body required via -m, STDIN, or -o message-file=FILE

Common:
  -t ADDRESS [ADDR ...]     to email address(es)
  -u SUBJECT                message subject
  -m MESSAGE                message body
  -s SERVER[:PORT]          smtp mail relay, default is localhost:25

Optional:
  -a   FILE [FILE ...]      file attachment(s)
  -cc  ADDRESS [ADDR ...]   cc  email address(es)
  -bcc ADDRESS [ADDR ...]   bcc email address(es)

Paranormal:
  -xu USERNAME              authentication user (for SMTP authentication)
  -xp PASSWORD              authentication password (for SMTP authentication)
  -l  LOGFILE               log to the specified file
  -v                        verbosity, use multiple times for greater effect
  -q                        be quiet (no stdout output)
  -o NAME=VALUE             see extended help topic "misc" for details

Help:
  --help TOPIC              The following extended help topics are available:
      addressing            explain addressing and related options
      message               explain message body input and related options
      misc                  explain -xu, -xp, and others
      networking            explain -s, etc
      output                explain logging and other output options

Upvotes: 6

Oli
Oli

Reputation: 1692

Send mail from Bash with one line:

echo "your mail body" | mail -s "your subject" [email protected] -a "From: [email protected]"

Upvotes: 6

Orwellophile
Orwellophile

Reputation: 13933

I whipped this up for the challenge. If you remove the call to 'dig' to obtain the mail relay, it is a 100% native Bash script.

#!/bin/bash
MAIL_FROM="[email protected]"
RCPT_TO="[email protected]"
MESSAGE=message.txt
SMTP_PORT=25
SMTP_DOMAIN=${RCPT_TO##*@}

index=1
while read PRIORITY RELAY
do
    RELAY[$index]=$RELAY
    ((index++))
done < <( dig +short MX $SMTP_DOMAIN )

RELAY_COUNT=${#RELAY[@]}
SMTP_COMMANDS=( "HELO $HOSTNAME" "MAIL FROM: <$MAIL_FROM>" "RCPT TO: <$RCPT_TO>" "DATA" "." "QUIT" )
SMTP_REPLY=([25]=OK [50]=FAIL [51]=FAIL [52]=FAIL [53]=FAIL [54]=FAIL [55]=FAIL [45]=WAIT [35]=DATA [22]=SENT)

for (( i = 1 ; i < RELAY_COUNT ; i++ ))
do
    SMTP_HOST="${RELAY[$i]}"
    echo "Trying relay [$i]: $SMTP_HOST..."
    exec 5<>/dev/tcp/$SMTP_HOST/$SMTP_PORT
    read HELO <&5
    echo GOT: $HELO
    for COMMAND_ORDER in 0 1 2 3 4 5 6 7
    do
            OUT=${SMTP_COMMANDS[COMMAND_ORDER]}
            echo SENDING: $OUT
            echo -e "$OUT\r" >&5

            read -r REPLY <&5
            echo REPLY: $REPLY
            # CODE=($REPLY)
            CODE=${REPLY:0:2}
            ACTION=${SMTP_REPLY[CODE]}
            case $ACTION in
                    WAIT )          echo Temporarily Fail
                                                    break
                                                    ;;
                    FAIL )          echo Failed
                                                    break
                                                    ;;
                    OK )                            ;;
                    SENT )          exit 0
                                                    ;;
                    DATA )          echo Sending Message: $MESSAGE
                                                    cat $MESSAGE >&5
                                                    echo -e "\r" >&5
                                                    ;;
                    * )         echo Unknown SMTP code $CODE
                                                    exit 2
            esac
    done
done

Upvotes: 8

Alok Singhal
Alok Singhal

Reputation: 96091

sendmail and even postfix may be too big to install if all you want to do is to send a few emails from your scripts.

If you have a Gmail account for example, you can use Google's servers to send email using SMTP. If you don't want to use gGoogle's server, as long as you have access to some SMTP server, it should work.

A very lightweight program that makes it easy to do so is msmtp. They have examples of configuration files in their documentation.

The easiest way to do it would be to set up a system-wide default:

account default
host smtp.gmail.com
from [email protected]
user [email protected]
password XXX
port 587

msmtp should be very easy to install. In fact, there is a port for it, so it could be as easy as port install msmtp.

After installing and configuring msmtp, you can send email to [email protected] using:

mail -s <subject> [email protected] <<EOF
<mail text, as many lines as you want. Shell variables will be expanded>.
EOF

You can put the above in a script. See man mail for details.

Upvotes: 3

docwhat
docwhat

Reputation: 11694

Here is a simple Ruby script to do this. Ruby ships on the Mac OS X versions you mentioned.

Replace all the bits marked 'replace'. If it fails, it returns a non-zero exit code and a Ruby back trace.

require 'net/smtp'

SMTPHOST = 'replace.yoursmtpserver.example.com'
FROM = '"Your Email" <[email protected]>'

def send(to, subject, message)
  body = <<EOF
From: #{FROM}
To: #{to}
Subject: #{subject}

#{message}
EOF
  Net::SMTP.start(SMTPHOST) do |smtp|
    smtp.send_message body, FROM, to
  end
end

send('[email protected]', 'testing', 'This is a message!')

You can embed this in a Bash script like so:

ruby << EOF
 ... script here ...
EOF

For some other ways to send Ruby emails, see Stack Overflow question How do I send mail from a Ruby program?.

You can use other languages that ship with Mac OS X as well:

Upvotes: 4

Brian Postow
Brian Postow

Reputation: 12167

Actually, "mail" works just as well.

mail -s "subject line" [email protected] < filename

works perfectly fine, as long as you have SMTP set up on your machine. I think that most Macs do, by default.

If you don't have SMTP, then the only thing you're going to be able to do is go through Mail.app. An ALTERNATIVE way to go through mail.app is via AppleScript. When you tell Mail.app to send mail via AppleScript you can tell it to not pop up any windows... (this does still require Mail.app to be configured).

Introduction to Scripting Mail has a good description of how to work with mail in AppleScript.

Upvotes: 41

Byron Whitlock
Byron Whitlock

Reputation: 53850

There is a program called Sendmail.

You probably don't want to use the -bs command unless you are sending it as raw SMTP like Martin's example. -bs is for running an SMTP server as a deamon. Sendmail will send directly to the receiving mail server (on port 25) unless you override it in the configuration file. You can specify the configuration file by the -C paramter.

In the configuration, you can specify a relay server (any mail server or sendmail running -bs on another machine)

Using a properly configured relay server is good idea because when IT manages mail servers they implement SPF and domain keys. That keeps your mail out of the junk bin.

If port 25 is blocked you are left with two options.

  1. Use the corporate SMTP server.
  2. Run sendmail -bd on a machine outside of the corporate firewall that listens on a port other than 25.

I believe you can add configuration parameters on the command line. What you want is the SMART_HOST option. So call Sendmail like sendmail -OSMART_HOST=nameofhost.com.

Upvotes: 15

Martin Olsen
Martin Olsen

Reputation: 1925

Probably the only way you could do this, while keeping the program self-sufficient, is if you have direct access to an SMTP server from the clients.

If you do have direct access to an SMTP server you can use the SMTP example from wikipedia and turn it into something like this:

#!/bin/bash
telnet smtp.example.org 25 <<_EOF
HELO relay.example.org
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
From: Joe <[email protected]>
To: Jane <[email protected]>
Subject: Hello

Hello, world!
.
QUIT
_EOF

To handle errors I would redirect the output from telnet to a file and then grep that for a "success message" later. I am not sure what format the message should be, but I see something like "250 2.0.0 Ok: queued as D86A226C574" in the output from my SMTP server. This would make me grep for "^250.*queued as".

Upvotes: 10

tmeisenh
tmeisenh

Reputation: 1534

Here's a modified shells script snip I've used on various UNIX systems... (echo "${MESSAGE}" | ${uuencode} ${ATTACHMENT}$basename ${ATTACHMENT}) | ${mailx} -s "${SUBJECT}" "${TO_LIST}"

uuencode and mailx are set to the executables. The other variables are from user input parsed using getopts.

This does work but I have to admit more often than not I use a simple Java program to send console emails.

Upvotes: 0

user3850
user3850

Reputation:

1) Why not configure postfix to handle outbound mail only and relay it via a mail gateway? Its biggest advantage is that it is already installed on OS X clients.

2) Install and configure one of the lightweight MTAs that handle only outbound mail, like nullmailer or ssmtp (available via MacPorts).

In both cases use mailx(1) (or mutt if you want to get fancy) to send the mails from a shell script.

There are several questions on Server Fault that go into the details.

Upvotes: 3

Related Questions