MIME Email with Attachment

creating MIME messages with attachment using Linux Shell

Yes, we Shell!

Sometimes, we may want to have our own MIMEs (as in Mail Extensions messages, although bossing around an entourage of stripy shirt artists may be fun) for use
with such programs as sendmail. While creating a simple text email using MIME is simple, adding attachments requires a bit of work and can be tricky. Thankfully, Linux Bash Shell gives us the
right tools to get the job done.

In this example, let’s say we want to add a .jpg file as an attachment to our MIME message.

Step 1 - Specify attachment

Step 2 - Determine MIME type

Now, we need to determine what MIME file type we are dealing with. One command we can use is gnomevfs-info which gives us the relevant file information. At the same time, we can use pattern-matching
command such as awk to find the specific information we are looking for.

Step 3 - Encode attachment

MIME requires us to encode the attachment in base-64. We can use uuencode command to do that. After the encoding, we would need to remove first and last lines, which specify start and end of encoding.
sed stream editor will help us easily remove those lines.

Step 4 - Create email boundary

A multi-part MIME message require boundaries between different parts of the message, and at the start and end of the message body. Boundary could be anything specified by boundary argument in Content-Type
MIME header. In our case, we will use the first 32 characters of MD5 checksum of current time in seconds as a message boundary, using md5sum command.