Python - How to send utf-8 e-mail?

前端 未结 2 1344
终归单人心
终归单人心 2020-11-30 00:05

how to send utf8 e-mail please?

import sys
import smtplib
import email
import re

from email.mime.multipart import MIMEMultipart
from email.mime.text import         


        
相关标签:
2条回答
  • 2020-11-30 00:36

    The question asked by Martin Drlík is 7 years and 8 months old... And nowadays, thanks to the developers of Python, encoding problems are solved with version 3 of Python.

    Consequently, it is no longer necessary to specify that one must use the utf-8 encoding:

    #!/usr/bin/python2
    # -*- encoding: utf-8 -*-
    ...
        part2 = MIMEText(text, "plain", "utf-8")
    

    We will simply write:

    #!/usr/bin/python3
    ...
        part2 = MIMEText(text, "plain")
    

    Ultimate consequence: Martin Drlík's script works perfectly well!

    However, it would be better to use the email.parser module, as suggested in email: Examples.

    0 讨论(0)
  • 2020-11-30 00:39

    You should just add 'utf-8' argument to your MIMEText calls (it assumes 'us-ascii' by default).

    For example:

    # -*- encoding: utf-8 -*-
    
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    msg = MIMEMultipart("alternative")
    msg["Subject"] = u'テストメール'
    part1 = MIMEText(u'\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\uff01\n',
                     "plain", "utf-8")
    msg.attach(part1)
    
    print msg.as_string().encode('ascii')
    
    0 讨论(0)
提交回复
热议问题