Volodymyr Zavada
Volodymyr Zavada

Reputation: 699

Ubuntu. Sending emails with embedded images

I have Ubuntu server(16.04) + Nagios, also I have created a script that makes a screenshot(Nagios status) every night and sends this screenshot to two recipients. But occurs problem, I receive mail with images(embed in a body, not attachment) - is OK, but my friend receives the same mail with broken images(blank files in attachment). Any suggestion, how to solve this problem? Script code:

    #!/bin/bash

cat <<EOT | /usr/sbin/sendmail -t
TO: @email1, @email2
SUBJECT: Report: Nagios Event Log  $(date +%F --date=yesterday)
MIME-Version: 1.0
Content-Type: multipart/related;boundary="XYZ"

--XYZ
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-15">
</head>
<body bgcolor="#ffffff" text="#000000">
Hello Team,<br>Daily Nagios report of $(date +%F --date=yesterday) is generated.
<img src="cid:part1.06090408.01060107" alt="">
<br>Best Regards, Nagios Admin
</body>
</html>

--XYZ
Content-Type: image/png;name="Nagios-EventLog-`date +%F --date="yesterday"`.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="Nagios-EventLog-`date +%F --date="yesterday"`.png"
$(base64 /some_path/NagiosReport/Nagios-EventLog-`date +%F --date="yesterday"`.png)
--XYZ--
EOT

Upvotes: 1

Views: 764

Answers (1)

tripleee
tripleee

Reputation: 189936

You lack a newline between the MIME headers and the base64 image data.

Running base64 in a command substitution inside a here document will probably produce overlong lines in the output. Try (rough pseudocode)

( cat <<EOF
  From: blah blah ...
  Subject: blah blah ...
  :
  --XYZ
  Content-description: image/png; name=etc etc

  EOF

  base64 file

  printf "\n--XYZ--\n" ) | sendmail -oi -t

(I'm assuming you did PATH=/usr/sbin:$PATH near the top of the script so you don't have to hard-code the path to sendmail.)

If improved knowledge of MIME isn't a personal development goal, probably use a program which knows how to do this properly. Many people use mutt to send mail on their behalf without having to worry about how exactly to do it right.

As a stylistic aside, running $(date +%F) multiple times seems clunky. Just run it once and capture the output in a variable. (In the pathological case, the script runs around midnight, and you get different dates in different parts of the message!)

Upvotes: 2

Related Questions