This blog contains experience gained over the years of implementing (and de-implementing) large scale IT applications/software.

HowTo: Script eMail With Attachment Direct via SMTP Server

Have you ever wondered how you can directly send an email with a file attachment, direct from a shell script via an SMTP server?
That is, without needing to rely on any mail or sendmail setup on the UNIX/Linux server.
Well, it’s simple.

Create a script that encodes the file you wish to attach, into BASE64, then type the following to send the file:

telnet somesmtpserver.net 25<<EOF
helo yourserver.net
mail from: noreply@mymail.net
rcpt to: noreply@mymail.net
data
Subject: Test attachment

Mime-Version: 1.0
Content-Type: multipart/mixed; boundary=attachmentbound

--attachmentbound
The email body

--attachmentbound
Content-Type: application/octet-stream; name="attachmentfile"
Content-Disposition: attachment; filename="thefilename.txt"
Content-Transfer-Encoding: base64

VGVzdCBBdHRhY2htZW50     <<-- Insert your BASE64 content here!

.
quit
EOF

You need to have the content already encoded in BASE64.
For this you could use a Perl script using the MIME::Base64 module as shown below:


#!/usr/bin/perl
use MIME::Base64;
#printf ("%s", encode_base64(eval ""$ARGV[0]""));

## Check to see if each and every file exists ##
foreach $file (@ARGV)
{
if (not -e $file)
{
print "File "$file" does not existn";
exit( 1 );
}

# Convert file to BASE64
open( OUTFILE, ">$file.out") or die "Could not open outputfile: $!n";;
open( FILE, $file ) or die "Could not open inputfile: $!n";
{
local($/) = undef;
print OUTFILE encode_base64(<FILE>);
}
close( FILE );
close( OUTFILE );
}