Issue with smtplib sending mail with unicode characters in Python 3.1

前端 未结 3 1615
悲哀的现实
悲哀的现实 2020-12-01 16:32

Hello i\' ve this problem with unicode emails, when i try to send words in spanish like: \"Añadir\" or others the system collapse, i\'ve try what says on this link: Python 3

3条回答
  •  囚心锁ツ
    2020-12-01 16:49

    I solved it, the solution is this:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    
    frm = "xxxx@xxxxxx.com"
    msg = MIMEMultipart('alternative')
    
    msg.set_charset('utf8')
    
    msg['FROM'] = frm
    
    bodyStr = ''
    to = "xxxx@xxxxxx.com"
    #This solved the problem with the encode on the subject.
    msg['Subject'] = Header(
        body.getAttribute('subject').encode('utf-8'),
        'UTF-8'
    ).encode()
    
    msg['To'] = to
    
    # And this on the body
    _attach = MIMEText(bodyStr.encode('utf-8'), 'html', 'UTF-8')        
    
    msg.attach(_attach)
    
    server.sendmail(frm, to, msg.as_string())
    
    server.quit()
    

    Hope this helps! Thanks!

提交回复
热议问题