简体   繁体   中英

How to send HTML email with attachment with sendmail software in UNIX ksh

I'm trying to send HTML email with an attachment but is not working, is just sending the file

the following code works with the HTML:

message="all the HTML message"
(
   echo "From: UnixMail@test.com";
   echo "To: emails@email.com";
   echo "Subject: Testing HTML with attachment";
   echo "Content-Type: text/html";
   echo "MIME-Version: 1.0";
   echo "";
   echo "${message}";
) | /usr/sbin/sendmail -t

but I'm trying to add the attachment like this:

message="all the HTML message"
(
   echo "From: UnixMail@test.com";
   echo "To: emails@email.com";
   echo "Subject: Testing HTML with attachment";
   echo "Content-Type: text/html";
   echo "MIME-Version: 1.0";
   echo "Content-Transfer-Encoding: base64"
   echo "Content-Type: application/octet-stream; name=test_file.txt"
   echo "Content-Disposition: attachment; filename=/directory/myfile"
   echo "";
   echo "${message}";
) | /usr/sbin/sendmail -t

Is not working, just send the attachment without any readable things... any idea?

 echo "Content-Transfer-Encoding: base64" ... echo "${message}"; 

Mail is restricted traditionally to ASCII data and a line length of 998 characters. This means that binary data need to be encoded to adhere to these limitations and that the type of encoding needs to be specified. Specifying the encoding is done with the Content-Transfer-Encoding header which you correctly set to base64 . The problem is that you don't encode the data as base64 then but instead just insert the original data. Most mail clients will in this case just ignore any characters not belonging to base64 (ie everything outside A-Za-z0-9/+ ) as garbage. The rest will be treated as base64 encoding and decoded accordingly, resulting in the junk data you see.

Thus you should not just include ${message} directly but instead first encode the message. This can be done using the base64 tool if available or with uuencode --base64 . But with uuencode you absolutely need to remove the prefix and postfix line and keep only the encoded data.

Apart from that you should probably do this with the HTML message too unless the message is already within the restrictions of only ASCII characters and a line length limit of 998 characters. It will probably work without encoding in most cases but might fail with some recipients, depending on the mail servers involved and the capabilities of the mail client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM