Saturday 28 May 2011

Sending email or mail with attachment from command or shell prompt


If you are looking to send email with attachment via shell script or at shell prompt/command line (read as bash prompt), use mutt command.
Mutt is a small but very powerful text based program for reading electronic mail under UNIX /Linux operating systems, including support for color terminals, MIME, and a threaded sorting mode.
Please note that mutt is a pure MUA and cannot send e-mail without proper email server . You need a working Mail Transfer Agent (MTA) such as sendmail or postfix. I am assuming that you have configured email server.

Install mutt

If mutt is not installed, use apt-get or yum or up2date command as follows (login as a root user):
(A) Debian Linux / Ubuntu Linux user use following command to install mutt:
# apt-get install mutt
B) Fedora / CentOS or Red Hat Linux (RHEL) user can use following command to install mutt:
# yum install mutt
OR
# up2date mutt
C) FreeBSD user use following command to install mutt via pkg_add command:
# pkg_add -v -r mutt

How do I send email attachments from a command prompt?

1) Use mutt command as follows to send an email with attachment:
$ mutt -s "Test mail" -a /tmp/file.tar.gz vivek@nixcraft.co.in < /tmp/mailmessage.txt
Where,
  • vivek@nixcraft.co.in – is the recipient
  • /tmp/mailmessage.txt – is the main body of the e-mail (read message from the file “mailmessage.txt”)
  • /tmp/file.tar.gz – is an attachment (with option -a)
  • “Test mail” – is a subject line (option -s)

SEND MAIL BASH SCRIPT

put in a shell script:

#!/bin/bash
# script to send simple email
# email subject
SUBJECT="SET-EMAIL-SUBJECT"
# Email To ?
EMAIL="admin@somewhere.com"
# Email text/message
EMAILMESSAGE="/tmp/emailmessage.txt"
echo "This is an email message test"> $EMAILMESSAGE
echo "This is email text" >>$EMAILMESSAGE
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE

No comments:

Post a Comment