本文介绍了Python - 如何发送utf-8电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如何发送utf8电子邮件?

  import sys 
import smtplib
import email
import re

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

def sendmail(firm,fromEmail,to,template,subject,date):
打开(template,encoding =utf-8)作为template_file:
message = template_file.read()

message = re.sub(r{{\s * firm \s *}},公司,消息)
message = re.sub(r{{\s * date\s *}},日期,消息)
message = re .sub(r{{\s * from\s *}},fromEmail,message)
message = re.sub(r{{\s * to\s *}} ,to,message)
message = re.sub(r{{\s * subject\s *}},主题,消息)

msg = MIMEMultipart(替代)
msg.set_charset(utf-8)

msg [Subject] = subject
msg [From] = fromEmail
msg [ to] = to

#从模板中读取
html = message [message.find(html:)+ l en(html:):message.find(text:)]。strip()
text = message [message.find(text:)+ len(text:):]。 strip()

part1 = MIMEText(html,html)
part2 = MIMEText(text,plain)

msg.attach(part1)
msg.attach(part2)

try:
server = smtplib.SMTP(10.0.0.5)
server.sendmail(fromEmail,[to],msg .as_string())
返回0
除了例外例外:
#log错误
#return -1
#debug
raise ex
最后:
server.quit()

如果__name__ ==__main__:
#debug
sys.argv.append(Moje)
sys.argv.append([email protected]
sys.argv.append([email protected]
sys.argv.append(may2011.template)
sys.argv.append(这是主题)
sys.argv.append(This is date)


如果len(sys.argv )!= 7:
exit(-2)

firm = sys.argv [ 1]
fromEmail = sys.argv [2]
to = sys.argv [3]
template = sys.argv [4]
subject = sys.argv [5]
date = sys.argv [6]

exit(sendmail(firm,fromEmail,to,template,subject,date))
pre>

输出

 >追踪(最近最近的通话):
>文件C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py,
>第69行在< module>
>退出(sendmail(公司,从电子邮件,模板,主题,日期))
>
>文件C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py,
>第45行,在sendmail
>提高ex
>
>文件C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py,
>第39行,在sendmail
> server.sendmail(fromEmail,[to],msg.as_string())
>
>文件C:\Python32\lib\smtplib.py,
>第716行,在sendmail
> msg = _fix_eols(msg).encode('ascii')UnicodeEncodeError:'ascii'codec
>
>不能在
>中编码字符'\\\ě'位置385:序号不在
>范围(128)


解决方案

你应该添加'utf-8'参数 MIMEText 调用(假设'我们ascii'默认)。



例如:

 # -  *  -  encoding:utf- 8  -  *  -  

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

msg = MIMEMultipart(alternative)
msg [Subject] = u'テストメール'
part1 = MIMEText(u'\\\こ\\\ん\\\に\\\ち\\\は\\\、\\\世\\\界\ uff01\\\
',
plain,utf-8)
msg.attach(part1)

打印msg.as_string()。encode('ascii' )


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 MIMEText

def sendmail(firm, fromEmail, to, template, subject, date):
    with open(template, encoding="utf-8") as template_file:
        message = template_file.read()

    message = re.sub(r"{{\s*firm\s*}}", firm, message)
    message = re.sub(r"{{\s*date\s*}}", date, message)
    message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
    message = re.sub(r"{{\s*to\s*}}", to, message)
    message = re.sub(r"{{\s*subject\s*}}", subject, message)

    msg = MIMEMultipart("alternative")
    msg.set_charset("utf-8")

    msg["Subject"] = subject
    msg["From"] = fromEmail
    msg["To"] = to

    #Read from template
    html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
    text = message[message.find("text:") + len("text:"):].strip()

    part1 = MIMEText(html, "html")
    part2 = MIMEText(text, "plain")

    msg.attach(part1)
    msg.attach(part2)

    try:
        server = smtplib.SMTP("10.0.0.5")
        server.sendmail(fromEmail, [to], msg.as_string())
        return 0
    except Exception as ex:
        #log error
        #return -1
        #debug
        raise ex
    finally:
        server.quit()

if __name__ == "__main__":
    #debug
    sys.argv.append("Moje")
    sys.argv.append("[email protected]")
    sys.argv.append("[email protected]")
    sys.argv.append("may2011.template")
    sys.argv.append("This is subject")
    sys.argv.append("This is date")


    if len(sys.argv) != 7:
        exit(-2)

    firm = sys.argv[1]
    fromEmail = sys.argv[2]
    to = sys.argv[3]
    template = sys.argv[4]
    subject = sys.argv[5]
    date = sys.argv[6]

    exit(sendmail(firm, fromEmail, to, template, subject, date))

Output

> Traceback (most recent call last):
> File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py",
> line 69, in <module>
>     exit(sendmail(firm, fromEmail, to, template, subject, date))
>
> File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py",
> line 45, in sendmail
>     raise ex
>
>   File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py",
> line 39, in sendmail
>     server.sendmail(fromEmail, [to], msg.as_string())
>
> File "C:\Python32\lib\smtplib.py",
> line 716, in sendmail
>     msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec
>
> can't encode character '\u011b' in
> position 385: ordinal not in
> range(128)
解决方案

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')

这篇关于Python - 如何发送utf-8电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 01:53