Extended Brain Storage

OpenBSD: Sendmail with Attachment from Shell

Posted on April 27, 2018

A script to achieve sending an e-mail with attachment from shell in OpenBSD

Introduction

The native sendmail command available in OpenBSD does not provide all the options known from versions available in other operating systems (e.g. -a to attach files). Therefore, a tiny workaround (script) needs to be done in order to achieve sending an e-mail with attachment from command-line interface (CLI).

The Script

OpenBSD uses ksh (public domain Korn shell) as the default shell. Most probably, the following script will work in other shells as well:

(echo -e "From: Name Surname <from@domain.tld>
Subject: The Subject of the E-mail
To: Name Surname <to@domain.tld>

The first line of the body (message),
the second line of the body of the e-mail." \
| sed 's/^[[:space:]]*//;s/[[:space:]]*\$//' \
; uuencode /path/to/file file-name) \
| sendmail -t


A couple of notes to the script:

• The echo command provides details regarding the sender and recipient including the subject field and message body.
• The sed command replaces from the echo command all trailing spaces, which were indented to provide better code transparency and understanding.
• The uuencode command (Unix-to-Unix encoding) is a software to performs binary-to-text encoding, which is used for data transmission in e-mail systems. Even though it has now been largely replaced by Multipurpose Internet Mail Extensions (MIME) with Base64 encoding and yEnc, it is sufficient for the aforementioned purposes.