function pack(m) for SMTP attachments

4 posts
by jimsuelamb1944 » Fri May 19, 2017 3:04 am
I used code found at the bottom of a tutorial at ... _email.htm to send an email with a large text attachment. The attachment was stored as a .txt file in my RPi system, in which I was running python 2.7, I was elated to successfully send and receive an email with the attachment using the instructions. I was dismayed that the attachment showed up in my Outlook as a huge block of characters that included small and capital alpha characters and numeric characters but no symbols (e.g., #$";\ - etc.). (There is maybe a clue in there, but I could not figure it out.) I then sent a very short .txt file that included only "1 2 3 4" (without the quotes).
It came across as "MSAyIDMgNA" (without the quotes). I converted this to hex but that lead to no revelation.
I went back to the tutorial and found this sentence: "Attached files should be encoded with the pack("m") function to have base64 encoding before transmission. I spent 15 minutes trying to find out what this meant, to no avail. The description of struct.pack includes no parameter "m". Can someone clarify what was meant by the sentence? Or more generally, what I should do to the file at the point in the given code where the attachment is opened so that it is received as text?
Jim Lamb
Posts: 6
Joined: Sat Mar 25, 2017 3:39 am
by rpdom » Fri May 19, 2017 4:11 am
It's Base64 encoding. It is used to encode 8-bit binary data using just printable characters. Each character represents 6 bits of the original data. The data is padded with zeroes which show up as "=" on the end to make the encoded form a multiple of 4 bytes long.

Your coded string appears to be missing a bit at the end. Either "==" if the line does not have a line feed on it, or "o=" if it does.

You can test it on the command line using the base64 command
Code: Select all
pi@raspi10:~ $ echo "1 2 3 4" | base64
pi@raspi10:~ $ echo "MSAyIDMgNAo=" | base64 --decode
1 2 3 4
User avatar
Posts: 10686
Joined: Sun May 06, 2012 5:17 am
Location: Essex, UK
by jimsuelamb1944 » Fri May 19, 2017 1:18 pm
Your explanation of the base64 coding is quite clear. Thankyou. I was hoping to find out how to prepare the text attachment so that when the email is received, it appears in its original form. That was what I thought the quoted sentence was suggesting, by referring to the use of something called python function pack(m).
Jim Lamb
Posts: 6
Joined: Sat Mar 25, 2017 3:39 am
by jimsuelamb1944 » Fri May 19, 2017 6:09 pm
Thanks to those who replied. Thankyou. I am still interested in what was meant by the quoted sentence. I am still interested in knowing how to send things other than text in a manner that they arrive looking as they did before being sent. I have however, solved my immediate problem by simply not encoding the text with base64 or anything else.
Jim Lamb
Posts: 6
Joined: Sat Mar 25, 2017 3:39 am