Reading EmailMessage from file

Cameron Simpson cs at cskk.id.au
Sun Jul 15 20:48:21 EDT 2018


On 15Jul2018 23:34, Jon Ribbens <jon+usenet at unequivocal.eu> wrote:
>On 2018-07-15, Skip Montanaro <skip.montanaro at gmail.com> wrote:
>> I have an email message in a file (see attached).
>
>Attachments don't work here.
>
>> something like this should construct an email message from the file:
>>
>>>>> from email.message import EmailMessage
>>>>> msg = EmailMessage()
>>>>> fp = open("/home/skip/tmp/79487694")
>>>>> msg.set_content(fp.read())
>
>What are you actually trying to do? You're talking like you're trying
>to read an existing RFC822 email-with-headers from a file, but you're
>showing code that creates a new email with body content set from
>a file, which is a completely different thing.

Also, RFC822 messages tend not to be Unicode themselves, _or_ ISO8859-1. Email 
message file tend to be 7-bit ASCII, with a (small, well defined) variety of 
methods for passing other text encodings though that form.

When I read a mail message from a file I do it like this:

  msg = email.parser.Parser().parse(msgfile, headersonly=headersonly)

where `msgfile` is an open file (just "open(pathname, errors='replace')"). That 
returns a Message object.

Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)



More information about the Python-list mailing list