[New-bugs-announce] [issue14047] UTF-8 Email Header
Michal Sladek
report at bugs.python.org
Sat Feb 18 08:23:28 CET 2012
New submission from Michal Sladek <michal at sladkovi.eu>:
Hello!
I am not a programmer so I appologize if I just don't understand the docs properly. I need to wirte a function which sends emails with utf-8 encoded subject and body. I tried something like this:
def sendMail (fromAddr, toAddr, subject, body = '', attachment = ''):
message = email.mime.multipart.MIMEMultipart()
message.add_header('From',fromAddr)
message.add_header('To',toAddr)
message['Subject'] = email.header.Header(subject,'utf-8')
if (body != ''):
msgPart = email.mime.text.MIMEText(body,'plain','utf-8')
message.attach(msgPart)
if (attachment != ''):
if os.path.exists(attachment) == True:
filename = attachment.rpartition(os.sep)[2]
fp = open(attachment,'rb')
msgPart = email.mime.base.MIMEBase('application','octet-stream')
msgPart.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(msgPart)
msgPart.add_header('Content-Disposition','attachment',filename=filename)
message.attach(msgPart)
if smtpPort == 25:
smtpCon = smtplib.SMTP(smtpSrv,smtpPort)
else:
smtpCon = smtplib.SMTP_SSL(smtpSrv,smtpPort)
if (smtpUser != '') and (smtpPass != ''):
smtpCon.login(smtpUser,smtpPass)
smtpCon.send_message(message,mail_options=['UTF8SMTP','8BITMIME'])
logger.info (_('Sent mail to: {0} with subject: {1}').format(toAddr,subject))
smtpCon.quit()
I realized that adding email subject this way somehow brokes the message, so that the plain text body of the message is not visible on receiving side. I had to chnage the code like this:
base64Subject = base64.b64encode(subject.encode('utf-8')).decode()
encodedSubject = '=?UTF-8?B?{0}?='.format(base64Subject)
message.add_header('Subject',encodedSubject)
Am I doing something wrong?
----------
messages: 153634
nosy: msladek
priority: normal
severity: normal
status: open
title: UTF-8 Email Header
type: behavior
versions: Python 3.2
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue14047>
_______________________________________
More information about the New-bugs-announce
mailing list