email with a non-ascii charset in Python3 ?

Christian Heimes lists at cheimes.de
Wed Aug 15 08:48:40 EDT 2012


Am 15.08.2012 14:16, schrieb Helmut Jarausch:
> Hi,
> 
> I'm sorry to ask such a FAQ but still I couldn't find an answer - neither in the docs nor the web.
> 
> What's wrong with the following script?
> 
> Many thanks for a hint,
> Helmut.
> 
> #!/usr/bin/python3
> #_*_ coding: latin1 _*_
> 
> import smtplib
> from email.message import Message
> import datetime
> 
> msg= Message()
> msg.set_charset('latin-1')
> msg['Subject'] = "*** Email Test ***"
> msg['From'] = "Email_Tester at numa-sv.igpm.rwth-aachen.de"
> msg['To']   = "jarausch at igpm.rwth-aachen.de"
> msg['Date'] = datetime.datetime.utcnow().strftime('%m/%d/%Y %I:%M:%S %p')
> 
> server= smtplib.SMTP("igpm.igpm.rwth-aachen.de")
> msg.set_payload("Gedanken über einen Test","iso-8859-1")

You mustn't combine set_charset() with set_payload() with a charset.
That results into invalid output:

>>> msg = Message()
>>> msg.set_payload("Gedanken über einen Test", "iso-8859-1")
>>> msg.as_string()
'MIME-Version: 1.0\nContent-Type: text/plain;
charset="iso-8859-1"\nContent-Transfer-Encoding:
quoted-printable\n\nGedanken =FCber einen Test'

>>> msg2 = Message()
>>> msg2.set_charset("iso-8859-1")
>>> msg2.set_payload("Gedanken über einen Test", "iso-8859-1")
>>> msg2.as_string()
'MIME-Version: 1.0\nContent-Type: text/plain;
charset="iso-8859-1"\nContent-Transfer-Encoding:
quoted-printable\n\nGedanken über einen Test'

Christian




More information about the Python-list mailing list