SUMMARY: Sending E-Mail With Attachments From A Script

From: Dave Warchol <Warchol_at_harthosp.org>
Date: Fri Mar 21 2003 - 10:09:43 EST
Thanks very much to everyone who responded (36 responses so far, in a
very short period of time).

Many, many options:

-------------------------------------------------------------------------------
>From Jesse Trucks:

We installed mutt and run:
mutt -a filename toaddress@domain.com < /dev/null

This has no body text, so replace the /dev/null with a file with
text, or start the command by piping output from something else into
it.
-------------------------------------------------------------------------------
>From Ken McKinlay:

You might want to take a look at the following pages for suggestions
and
ideas:

Sending email with attachments on UNIX systems:
http://www3.primushost.com/~kylet/unix-att.html 
Sending files as mail attachments:
http://www.shelldorado.com/articles/mailattachments.html 

I found both of these sites as links from Stokely Consulting's great
site at
http://www.stokely.com/ 
-------------------------------------------------------------------------------
>From Shawn Evans:

sending mail is the easy part..

cat or echo your data..

echo blah | mail -s subject you@somesite.com 

but attatching a file has a trick, for the contents of cat to NOT be in
the
body of the message, tar or gzip, or both the file in question..

tar cvf file ; cat file | mail -s subject you@somesite.com 
-------------------------------------------------------------------------------
>From Carl Gobo:

Look at metamail.  metasend is the command line program to actually
send the
file as an attachment.

Here is the important line in my script to do it.

${METASEND} -b -s "${SUBJECT}" -S 1000000 -f ${TEMPFILE} -m
application/binary\; name=\"${FILENAME}\" -D ${FILENAME} -t ${MAILTO}
-c
-------------------------------------------------------------------------------
>From Francisco Puente:

Hi, You just can use uuencode:

#uuencode file1.bin file1.bin | mail -s "This is the subject"
some@email.address.com 

Use can use it from the command line or from any script, and can use
mail or
mailx application to send the email.
-------------------------------------------------------------------------------
>From Raj Dilipsinh:

Here is how you Send Attachments:

mail root << EOF
To:     addr@abc.com 
Reply:  addr@abc.com 
From: 	sender@abc.com 
Subject: This is a test
Message-Id: <MessgeId>
Content-Type: multipart/alternative;
    boundary="THIS_IS_THE_BREAK"
X-UIDL: <MessgeId>

--THIS_IS_THE_BREAK
Content-type: text/text;
    name="$ATTACHED_FILE"
Content-Disposition: attachment;
    filename="$ATTACHED_FILE"

`cat $ATTACHED_FILE`

EOF

-------------------------------------------------------------------------------
Use mpack:

usage: mpack [-s subj] [-d file] [-m maxsize] [-c content-type] file
address...
       mpack [-s subj] [-d file] [-m maxsize] [-c content-type] -o file
file
       mpack [-s subj] [-d file] [-m maxsize] [-c content-type] -n
groups file
-------------------------------------------------------------------------------
>From Jason Shatzkamer:

Hey Dave,

Here is what you're looking for:

#!/usr/local/bin/perl

use MIME::Entity;

# Read in configuration data

$to_address = $ARGV[0];      # Address to send mail TO
$subject = $ARGV[1];         # Subject
$file = $ARGV[2];            # File to attach
$message = $ARGV[3];	     # Message to include with body


# Create an entity.  It's that "multipart/mixed" MIME type that makes
# all the difference to Notes.
$top = build MIME::Entity Type     => 'multipart/mixed',
                          From     => 'From@domain.com',
                          To       => "$to_address",
                          Subject  => "$subject";

# Attach the inline text to it:
$top->attach(Data        => "$message";,
             Type        => 'text/plain',
             Disposition => 'inline',
             Encoding    => 'quoted-printable');

$top->attach(Path        => "$file",
             Type        => 'application/octet-stream',
             Disposition => 'attachment',
             Encoding    => 'quoted-printable');

open MAIL, "|/usr/lib/sendmail -f Sequoia -oi -t -od";     #Pipe for
the
message

# Output it:
$top->print(\*MAIL);
close MAIL;

-------------------------------------------------------------------------------
>From Jay Lessert:

% echo "Here is an enclosure" | mutt -a file -s subject
Warchol@harthosp.org 

% mpack -s subject -d "Here is an enclosure" file Warchol@harthosp.org


Source from the usual places...
-------------------------------------------------------------------------------
>From Sean Berry:

There are other tools, but there's always uuencode, which most mail
clients have understood for years, if not over a decade.
-------------------------------------------------------------------------------
>From Timothy Lorenc:

Look at a Companion CD-ROM application [package] called: mpack
-------------------------------------------------------------------------------
>From Siva Santhakuma:

One Line script is:
When attaching a file to an email you nned to encode the attachement,
so one
line script is:

uuencode <att_file> <att_file> | mailx -s "SUBJECT"
someone@somewhere.com 

You can use the same name (att_file) or a different name but remeber
that
the second name will be send to the receiver.

To do it in a web format email attachement

#!/usr/bin/ksh
TO=someone@somewhere.com 
HTML_FILE=`ls batch.*.html | head -n 1`
HTML_FILE2=`ls sysout.*.html | head -n 1`
cat << EOF4 | /usr/lib/sendmail -t
From: myself@mydomain.com 
To: $TO
Cc: $CC
Subject: $SUBJECT
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="- boundry -"

--- boundry -
Content-Type: text/plain; charset=us-ascii

"Attached files"

--- boundry -
Content-Type: text/html; name=$(basename "$HTML_FILE")
Content-Transfer-Encoding: http
Content-Description: $(basename "$HTML_FILE")
Content-Disposition: attachment; $(basename "$HTML_FILE")

<HTML>
`cat $HTML_FILE`
</HTML>

--- boundry -
Content-Type: text/html; name=$(basename "$HTML_FILE2")
Content-Transfer-Encoding: http
Content-Description: $(basename "$HTML_FILE2")
Content-Disposition: attachment; $(basename "$HTML_FILE2")

<HTML>
`cat $HTML_FILE2`
</HTML>

--- boundry -
EOF4

##########End of Script
-------------------------------------------------------------------------------
>From Tim Chipman:
hey,

see attached for "msg_send", a small script that came through the list

~2 years ago, does what you seek. Works fine for me ...

please excuse my comments (added in the script) - I always document 
when/where/why a script comes into play.

#!/bin/sh
#****************************************************************************
#** Sun Microsystems Inc.                                              
   **
#** File:        mail_file                                             
   **
#** Type:        Bourne Shell                                          
   **
#** Purpose:     Command used to send an email, passing the named file
as  **
#**              an OWN V3 Mailtool "Attachment".                      
   **
#**                                                                    
   **
#**              This file takes the following 4 parameters:           
   **
#**                                                                    
   **
#**                     1 - TO            (ex: joe.jones@sybase.com)   
   **
#**                     2 - SUBJECT       (ex: "Here's your file")     
   **
#**                     3 - MESSAGE_FILE  (ex: /tmp/message_file)      
   **
#**                     4 - ATTACH_FILE   (ex: /tmp/attach_file)       
   **
#**                                                                    
   **
#****************************************************************************

##
## This script was setup by TDC on Nov-29-2000 upon request from Z.Z
for
## some means of e-mailing an attachment somehow*. His case required
only
## capacity to do a text message but this script is capable of
building
## a mime-encoded attachment (for a binary attachment) if requred
##
## The script was obtained via the SunManagers mailing list :-)
##
## (*) - via command line of course!

TO=$1

SUBJECT=$2
MESSAGE_FILE=$3
ATTACH_FILE=$4


#---------------------------------------------------------------------
# Function:     build_header_text()
# Description:  Creates a "Text" attachment out of the passed MESSAGE
file.
# Returns:      Sets $TotalLines to the total number of lines so far,
#               and cat's the header text into /tmp/$$-x.

#---------------------------------------------------------------------

build_header_text () {

# Get the text message length, etc.
LinesValue=`wc -l $MESSAGE_FILE  | nawk '{ print $1 }'`
LengthValue=`wc -c $MESSAGE_FILE | nawk '{ print $1 }'`
TotalLines=`echo "$LinesValue 5 + p" | dc`
TotalLength=LengthValue

# Copy the correct header information into the output file
echo "----------"                         >> /tmp/$$-x
echo "X-Sun-Data-Type: text"              >> /tmp/$$-x
echo "X-Sun-Data-Description: text"       >> /tmp/$$-x
echo "X-Sun-Data-Name: text"              >> /tmp/$$-x
echo "X-Sun-Content-Lines: "$LinesValue   >> /tmp/$$-x
echo "X-Sun-Content-Length: "$LengthValue >> /tmp/$$-x
echo ""                                   >> /tmp/$$-x
cat $MESSAGE_FILE                         >> /tmp/$$-x
echo "----------"                         >> /tmp/$$-x

} # end build_header_text



#---------------------------------------------------------------------
# Function:     determine_file_type()
# Description:  Figures out whether this is a Postscript, Cshell, 
#               Bourne shell, or Text file.  
# Returns:      Sets $FileType to a value suitable for using in the 
#               header of an Attachment.
#---------------------------------------------------------------------

determine_file_type () {

# Get the first line of the Attachment file
FirstLine=`cat $ATTACH_FILE | nawk '{ if (NR == 1) print $1, $2; }'`

# Determine the type of file it is
if echo $FirstLine | grep "PS" > /dev/null
then
   FileType="postscript-file"
elif echo $FirstLine | grep "/bin/csh" > /dev/null
then
   FileType="cshell-script"
elif echo $FirstLine | grep "/bin/sh" > /dev/null
then
   FileType="shell-script"
else
   FileType="text"
fi

} # end determine_file_type



#---------------------------------------------------------------------
# Function:     append_file()
# Description:  Appends file to end of work file.
# Returns:      Increments $TotalLines by the number of lines in file.
#               Appends file itself to /tmp/$$-x.
#---------------------------------------------------------------------

append_file () {

determine_file_type

LinesValue=`wc -l $ATTACH_FILE | nawk '{ print $1 }'`
LengthValue=`wc -c $ATTACH_FILE | nawk '{ print $1 }'`
TotalLines=`echo "$TotalLines $LinesValue + p" | dc`


SHORTNAME=`basename $ATTACH_FILE`; export SHORTNAME

echo "X-Sun-Data-Type: $FileType"               >> /tmp/$$-x
echo "X-Sun-Data-Name: "$SHORTNAME              >> /tmp/$$-x
echo "X-Sun-Content-Lines: "$LinesValue         >> /tmp/$$-x
echo "X-Sun-Content-Length: "$LengthValue       >> /tmp/$$-x
echo ""                                         >> /tmp/$$-x
cat $ATTACH_FILE                                >> /tmp/$$-x

}



#---------------------------------------------------------------------
# Function:     assemble_enchilada()
# Description:  Builds a file from the subject lines, total
#               length, and concatenated attachments.
# Returns:      Creates /tmp/$$-outbound file.
#---------------------------------------------------------------------

assemble_enchilada () {

echo "To: " $TO                         >  /tmp/$$-outbound
echo "Subject: "$SUBJECT                >> /tmp/$$-outbound
echo "Content-Type: X-sun-attachment"   >> /tmp/$$-outbound
echo "X-Lines: "$TotalLines             >> /tmp/$$-outbound
echo ""                                 >> /tmp/$$-outbound
cat /tmp/$$-x                           >> /tmp/$$-outbound

}



#---------------------------------------------------------------------
# Main program execution
#---------------------------------------------------------------------

build_header_text
append_file
assemble_enchilada

cat /tmp/$$-outbound  | /usr/lib/sendmail -t 

rm -f /tmp/$$-*

-------------------------------------------------------------------------------
>From Gaziz Nugmanov:

mpack helps
-------------------------------------------------------------------------------
>From Jim Vandevegt:

Offhand, I'd use a program called mpack which knows how to Base64
encode and MIME attach binaries.

I checked my source file. Available at
ftp://ftp.andrew.cmu.edu/pub/mpack/. 

It's very easy to use, a couple minutes with the man page will give you
all the options you need to drive it completely from the scripted
command line.

It shouldn't matter what the MTA is, but I know it works with sendmail
'cause that's what I use.
-------------------------------------------------------------------------------
>From Angel Alejandro Vega Soto:

check the man pages of uuencode and uudecode
-------------------------------------------------------------------------------
>From Chris Wianecki:

I think simplest way would be to use
uuencode, uudecode - encode a binary  file,  or  decode  its encoded
representation

And then pipe it to an email.
-------------------------------------------------------------------------------
>From Christian Campbell:

Download and install Mutt.  It is a powerful email client that allows
you to
attach files from the command line.

A command line help from Mutt:

usage: mutt [ -nRzZ ] [ -e <cmd> ] [ -F <file> ] [ -m <type> ] [ -f
<file> ]
       mutt [ -nx ] [ -e <cmd> ] [ -a <file> ] [ -F <file> ] [ -H
<file> ] [
-i <file> ] [ -s <subj> ] [ -b <addr> ] [ -c <addr> ] <addr> [ ... ]
       mutt [ -n ] [ -e <cmd> ] [ -F <file> ] -p
       mutt -v[v]

options:
  -a <file>     attach a file to the message
  -b <address>  specify a blind carbon-copy (BCC) address
  -c <address>  specify a carbon-copy (CC) address
  -e <command>  specify a command to be executed after initialization
  -f <file>     specify which mailbox to read
  -F <file>     specify an alternate muttrc file
  -H <file>     specify a draft file to read header from
  -i <file>     specify a file which Mutt should include in the reply
  -m <type>     specify a default mailbox type
  -n            causes Mutt not to read the system Muttrc
  -p            recall a postponed message
  -R            open mailbox in read-only mode
  -s <subj>     specify a subject (must be in quotes if it has spaces)
  -v            show version and compile-time definitions
  -x            simulate the mailx send mode
  -y            select a mailbox specified in your `mailboxes' list
  -z            exit immediately if there are no messages in the
mailbox
  -Z            open the first folder with new message, exit
immediately if
none
  -h            this help message
-------------------------------------------------------------------------------
>From Brian Dunbar:

man mailx

or

http://www.csam.montclair.edu/Docs/Users_guide/sun.mailx.html 

no, seriously, it's dead easy.

-------------------------------------------------------------------------------
>From Steve Sandau:
Here's the script I threw together to send attachments. It's kind of a
hack and only uses uuencode instead of mpack, but it has wroked OK for a
while...

#!/bin/sh
# sendattach
# to mail an attachment with sendmail
# 2/25/00, sss
#
# $1 is file to mail
# $2 is subject of message
# $3 is recipient
# $4 is the directory holding the file to attach
#
# check for correct number of arguments
if [ -z "$3" ]; then
  echo
  echo Usage: sendattach file subject recipient path_to_file
  echo
  exit
fi
# first put header stuff into temp file
# name temp file same as report in /tmp directory
echo Subject: $2 > /tmp/$1
echo >> /tmp/$1
echo Content-Type: application/octet-stream >> /tmp/$1
echo name=$1 >> /tmp/$1
echo Content-Transfer-Encoding: x-uuencode >> /tmp/$1
echo Content-Disposition: attachment >> /tmp/$1
echo filename=$1 >> /tmp/$1
#
# encode the file and put it with the header info
/usr/bin/uuencode $4/$1 $1 >> /tmp/$1
#
# now mail the file
/usr/lib/sendmail $3 < /tmp/$1
#
# clean up
rm /tmp/$1
-------------------------------------------------------------------------------
>From Ben Green:

check out mutt.

http://www.mutt.org/ 
-------------------------------------------------------------------------------
>From John Adams:

See here:

http://perl.about.com/library/weekly/aa042302a.htm
-------------------------------------------------------------------------------
>From Tim:

You can simply redirect the content into mail.

mail dave <  `echo "What you want to say"`
worked for me.
-------------------------------------------------------------------------------
>From Michael Schulte:

Look at the package "metamail"  (sunfreeware.com has one for Sol 7)
It includes a command "mailto" that lets you send mime-encoded
attachments.

-------------------------------------------------------------------------------
>From Andrew Caines:

Attachment implies MIME, so you need a MIME capable MUA or tool.

Mutt[1] is a very capable MUA and can send multiple attachments very
simply, eg.

	mutt $address -a $file1 -a $file2 < message

There are also a variety of tools for handling MIME which you can use
in
combination with your MTA (sendmail), such as the old mpack[2] and
gmime[3].

If you were scripting in perl, then there are a ton of MIME modules.

If you really want to DIY in the shell script, refer to the MIME
RFCs[4]
and simply put in the relevant headers and separators between your
encoded
data to make your message, then feed it to your MTA.


[1] http://www.mutt.org/ 
[2] http://www.netsw.org/net/mail/format/mime/mpack/ 
[3] http://spruce.sourceforge.net/gmime/ 
[4] See [3] for list
-------------------------------------------------------------------------------
>From Karl Vogel:

  Try the script below.  Requires perl plus File::Basename and
   MIME::Lite modules.

   http://www.dnaco.net/~vogelke/Software/Code/Perl/Mail/msend/ 

-------------------------------------------------------------------------------
>From Nelson Arzola:

If you have perl (which you do if you have Solaris 2.8 or higher, you
can find information here:

http://www.akadia.com/services/email_attachments_using_perl.html 

Note, these instructions are biased toward Windows.  To installed the
MIME::Lite package on Solaris, you type:

perl -MCPAN -e shell;

I'll leave it to you to walk through and answer the configuration
questions -- I don't think they are too hard, but if you need help ask.

After you get through the config, type:

cpan> install MIME::Lite

You'll need to do this as root.  When it finishes, you will be able to
use the script that this link mentions.  NOTE:  sometimes the CPAN
module will want to upgrade your version of Perl.  Solaris will not be
happy if you do this.  Since I always install a second copy of Perl on
my servers rather than mess with the one provided with Solaris, I don't
have information on how to prevent CPAN from doing this.  You can safely
install a second copy of Perl on Solaris 2.8 and higher without worrying
about system tools breaking because they have the path to the Solaris
copy hard coded within them.

You may also need Net::SMTP which you can get with this command:

cpan> install Net::SMTP
-------------------------------------------------------------------------------
>From Bertrand Hutin:

use mpack, available on sunfreeware.com
-------------------------------------------------------------------------------
>From Lucien Hercaud:

% tar cf /tmp/myfiles.tar fic1 dir2/ ....
% compress /tmp/myfiles.tar
% uuencode /tmp/myfiles.tar.Z /tmp/myfiles.tar.Z > /tmp/myfiles.uue
% mailx -v -s "my files" dest@add.net < /tmp/myfiles.uue
-------------------------------------------------------------------------------
>From Lars Hecking:

 http://www.mutt.org/
-------------------------------------------------------------------------------
>From Carl Shelin:

uuencode [file] [file] | mailx -s "Sending an attachment" [e-mail
addr]
-------------------------------------------------------------------------------
>From John Julian:

Attached is the script I use. 
You need to change the "From" address to your domain.
You may also need to change the content-type. I hard coded
"text/plain"
because that works for text and html attachments.

#!/bin/ksh
# attachmail by john julian Feb 26, 2002
Syntax='syntax: attachmail -a "attachmentname" -r "returnaddress" [ -s
"subject" ] 
   [ -m "message" ] recipient'

TempFile="/tmp/attachmail$$"

# get the command line args
while [ -n "$1" ]
do
  case "$1" in
    "-a" ) if [ -f "$2" ]
           then
             Attachment="$2"
             shift 2
           else
             print "ERROR no attachment file"
             exit
           fi;;
    "-r" ) From="$2"
           shift 2
           ;;
    "-s" ) Subject="$2"
           shift 2
           ;;
    "-m" ) Message="$2"
           shift 2
           ;;
    *    ) Recipient="$Recipient $1"
           shift
           ;;
  esac
done

if [[ $Recipient != *@* ]]
then
  print "ERROR invalid email address: $Recipient"
  print "$Syntax"
  exit
fi

if [ -z "$From" ]
then
  From="$( whoami )@sbc.com"
fi

# put the headers in a temp file
print "Mime-Version: 1.0
To: $Recipient
Subject: $Subject
Content-Type: multipart/mixed; boundary=boundarystring
--boundarystring
Content-Type: text/plain
" > $TempFile

# if we have a message then add it to temp file
if [ -n "$Message" ]
then 
  print -- "$Message" >> $TempFile
fi

# add the attachment header
print -- "--boundarystring
Content-Type: text/plain
Content-Disposition: attachment; filename=$Attachment\n" >> $TempFile

# now the file itself
cat "$Attachment" >> $TempFile

print -- "--boundarystring--" >> $TempFile

/usr/lib/sendmail -f "$From" -t < $TempFile
/bin/rm $TempFile

-------------------------------------------------------------------------------
>From Kevin Metzger:

My database folks are using a perl module to do just that.  Module
name
MIME Lite .

-------------------------------------------------------------------------------
>From Frank Flamingo:

Below is a sample script I've used that may help in getting you
started.

#!/bin/sh
#
# script to package a file into a mime entry for mailing
# FGF 2001.03.14
#
#!/bin/sh
#
# script to package a file into a mime entry for mailing
# FGF 2001.03.14
#
PATH=/usr/bin
file=sample.txt
tmp=/tmp/mime.$$
sender=sendaddr@domain.your.net 
sname="Lastname, Firstname"
replyto=support@domain.your.net 
recipient=recaddr@whereever.net 
subj="Sample File"
date=`date +"%a, %d %b %Y %H:%M:%S -0500"`

echo "From: \"$sname\" <$sender>" > $tmp
echo "To: \"$recipient\" <$recipient>" >> $tmp
echo "Subject: $subj" >> $tmp
echo "Date: $date" >> $tmp
cat << EOF1 >> $tmp
MIME-Version: 1.0
X-Mailer: Internet Mail Service (5.5.2650.21)
Content-Type: multipart/mixed;
        boundary="----_=_NextPart_000_01C09C08.5CE58FD6"

------_=_NextPart_000_01C09C08.5CE58FD6
Content-Type: text/plain;
        charset="iso-8859-1"

------_=_NextPart_000_01C09C08.5CE58FD6
Content-Type: text/plain;
        name="sample.txt"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
        filename="sample.txt"

EOF1

cat $file >> $tmp
-------------------------------------------------------------------------------
Charles Homan:

The general way I did it was to uuencode my attachments and output them
all
to a temp file.  I then used mailx to send it with input from my temp
file.

-------------------------------------------------------------------------------
>From Andrew Rotramel:

mpack is a utility that lets you send attachments with Unix mail, and
you
can script with it. I think it is sunfreeware.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
Thanks everyone............
Dave

==========Original Post=====================
Hello:
         I am looking for examples/links/howtos.  Goal is to be able to
send e-mail with attachments from a shell script.  MTA is sendmail.

Thanks
Dave
_______________________________________________
sunmanagers mailing list
sunmanagers@sunmanagers.org
http://www.sunmanagers.org/mailman/listinfo/sunmanagers
Received on Fri Mar 21 10:15:08 2003

This archive was generated by hypermail 2.1.8 : Thu Mar 03 2016 - 06:43:07 EST