This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author msladek
Recipients msladek
Date 2012-02-18.07:23:27
SpamBayes Score 0.015344006
Marked as misclassified No
Message-id <1329549808.72.0.457462714436.issue14047@psf.upfronthosting.co.za>
In-reply-to
Content
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?
History
Date User Action Args
2012-02-18 07:23:28msladeksetrecipients: + msladek
2012-02-18 07:23:28msladeksetmessageid: <1329549808.72.0.457462714436.issue14047@psf.upfronthosting.co.za>
2012-02-18 07:23:28msladeklinkissue14047 messages
2012-02-18 07:23:27msladekcreate