How to set a charset in email using smtplib in Python 2.7?

前端 未结 3 596
渐次进展
渐次进展 2020-12-13 10:31

I\'m writing a simple smtp-sender with authentification. Here\'s my code

    SMTPserver, sender, destination = \'smtp.googlemail.com\', \'user@gmail.com\', [         


        
3条回答
  •  执念已碎
    2020-12-13 11:03

    from email.header import Header
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    def contains_non_ascii_characters(str):
        return not all(ord(c) < 128 for c in str)   
    
    def add_header(message, header_name, header_value):
        if contains_non_ascii_characters(header_value):
            h = Header(header_value, 'utf-8')
            message[header_name] = h
        else:
            message[header_name] = header_value    
        return message
    
    ............
    msg = MIMEMultipart('alternative')
    msg = add_header(msg, 'Subject', subject)
    
    if contains_non_ascii_characters(html):
        html_text = MIMEText(html.encode('utf-8'), 'html','utf-8')
    else:
        html_text = MIMEText(html, 'html')    
    
    if(contains_non_ascii_characters(plain)):
        plain_text = MIMEText(plain.encode('utf-8'),'plain','utf-8') 
    else:
        plain_text = MIMEText(plain,'plain')
    
    msg.attach(plain_text)
    msg.attach(html_text)
    

    This should give you your proper encoding for both text and headers regardless of whether your text contains non-ASCII characters or not. It also means you won't automatically use base64 encoding unnecessarily.

提交回复
热议问题