Bobcares

How to Send Mail with Attachment in Shell Script Using Sendmail Command?

by | Oct 14, 2024

To send an email with an attachment using the sendmail command in a shell script, we can follow the steps explained in this article. Bobcares, as a part of our Server Management Service offers solutions to every query that comes our way.

Overview
  1. Sendmail Command in Shell Script to Send a Mail with an Attachment
  2. Sendmail Command in Shell Script to Send a Mail with Multiple Attachments
  3. Possible Issues & Fixes
  4. How to Test the Script?
  5. Conclusion

Sendmail Command in Shell Script to Send a Mail with an Attachment

In Linux, the sendmail command is a useful tool for sending emails from shell scripts or the command line. Sendmail is simple to use in its basic form, however sending an email with an attachment takes a little more effort because sendmail does not directly support attachments. But, we can obtain this by using MIME (Multipurpose Internet Mail Extensions) format for the email and encoding the attachment. The steps to send the mail with attachment using Sendmail command is as follows:

1. Prepare the email body: The email body must be written first, together with headers such as From, To, Subject, and the attachment within a MIME framework.

2. Use sendmail to Deliver the Email: Once the email has been prepared correctly, we may send it by piping the message to sendmail.

sendmail command with attachment in shell script

An Example

#!/bin/bash




# Define email variables

FROM="sender@example.com"

TO="recipient@example.com"

SUBJECT="This is a test email with attachment"

BODY="This is the body of the email."

ATTACHMENT="/path/to/your/file.txt"

FILENAME=$(basename "$ATTACHMENT")

BOUNDARY="ZZ_/afg6432dfgkl.94531q"




# Create the email header and body

{

  echo "From: $FROM"

  echo "To: $TO"

  echo "Subject: $SUBJECT"

  echo "MIME-Version: 1.0"

  echo "Content-Type: multipart/mixed; boundary=\"$BOUNDARY\""

  echo ""

  echo "--$BOUNDARY"

  echo "Content-Type: text/plain; charset=US-ASCII"

  echo "Content-Transfer-Encoding: 7bit"

  echo ""

  echo "$BODY"

  echo ""

  

  # Add the attachment

  echo "--$BOUNDARY"

  echo "Content-Type: application/octet-stream; name=\"$FILENAME\""

  echo "Content-Transfer-Encoding: base64"

  echo "Content-Disposition: attachment; filename=\"$FILENAME\""

  echo ""

  # Encode the attachment using base64

  base64 "$ATTACHMENT"

  echo ""

  

  # End the email

  echo "--$BOUNDARY--"

  

} | sendmail -t

The explanation of the script is as follows:

Headers: Includes sender (From), recipient (To), and Subject.

MIME: Uses MIME format to support attachments.

Email Body: Plain text section.

Attachment: Encoded in base64 and added as a separate section.

Sendmail: Pipes the complete email to sendmail -t to send it.

We must also make sure sendmail is installed and configured correctly on the system.

Sendmail Command in Shell Script to Send a Mail with Multiple Attachments

We just need to repeat the MIME section for each file to send several attachments. For example:

echo "--$BOUNDARY"

echo "Content-Type: application/octet-stream; name=\"file1.txt\""

echo "Content-Transfer-Encoding: base64"

echo "Content-Disposition: attachment; filename=\"file1.txt\""

echo ""

base64 "/path/to/file1.txt"

echo ""




echo "--$BOUNDARY"

echo "Content-Type: application/octet-stream; name=\"file2.pdf\""

echo "Content-Transfer-Encoding: base64"

echo "Content-Disposition: attachment; filename=\"file2.pdf\""

echo ""

base64 "/path/to/file2.pdf"

echo ""

Each attachment gets its own MIME boundary, type, and base64-encoded content.

Base64 Encoding: Including non-text files (such PDFs, pictures, etc.) as email attachments requires base64, a command-line tool that translates binary data into ASCII text. Email protocols were initially intended to handle text-based data, hence encoding is required since binary data must be transformed into a secure format before being sent. Within the script:

base64 “$ATTACHMENT”

Before attaching the file to the email body, this command encodes it in base64 format.

Possible Issues & Fixes

1. File Not Found: An error will appear if the file path to the attachment is not right. Verify the file exists and that the path to the attachment is correct.

2. Un-Installed Sendmail: We can install sendmail using the package management if it’s not installed on the server:

On Ubuntu/Debian:

sudo apt install sendmail

On CentOS/RHEL:

sudo yum install sendmail

3. Sendmail Configuration: To send emails, make sure the sendmail service is set up properly. Usually, this entails configuring an MTA (Mail Transfer Agent) on the server.

4. Email Clients Blocking Attachments: Certain file types (such as.exe files) or big attachments may be blocked by some email clients or servers. If this problem persists, check the settings on the client or server.

How to Test the Script?

To help in debugging, we can change the script so that it prints the contents of the email to the terminal rather than sending it. In place of the sendmail line, use:

} > /tmp/email.txt

This allows us to examine the newly created email before sending it by saving it to /tmp/email.txt.

[Need to know more? We’re available 24/7.]

Conclusion

In conclusion, we must set up the email using MIME format in order to send an attachment using sendmail on Linux. Creating email headers, base64 encoding the attachment, and sending it via sendmail are the steps in this process. Multiple attachments can be added using this method, but it does require path setup and suitable system setup for sendmail. So, we’ve to check file paths and make sure sendmail is installed and set correctly in order to debug.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF