有几个类似功能的 示例,我一直遵循这些准则,但这仍然不起作用。我试图让这个测试脚本运行:
# -*- coding: utf-8 -*-
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
USERNAME = 'you@gmail.com'
PASSWORD = 'yourpass'
COMMASPACE = ', '
SERVER = 'smtp.gmail.com:587'
def isallascii(str):
'''Checks if all characters in string are ascii (useful for unicode related processing)'''
return all(ord(c) < 128 for c in str)
def correct_headervalue(headervalue):
return headervalue if isallascii(headervalue) else Header(headervalue, 'utf-8')
def addheader(msg, headername, headervalue):
msg[headername] = correct_headervalue(headervalue)
def buildmsg(sender, receivers, subject, plainbody):
receivers_str = COMMASPACE.join(receivers) if receivers else None
msg = MIMEMultipart('alternative')
addheader(msg, 'Subject', subject)
addheader(msg, 'From', sender)
addheader(msg, 'To', receivers_str)
plaintext = MIMEText(plainbody,'plain') if isallascii(plainbody) else MIMEText(plainbody.encode('utf-8'), 'plain', 'utf-8')
msg.attach(plaintext)
return msg
smtpObj = smtplib.SMTP(SERVER)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(USERNAME, PASSWORD)
sender = 'Juan Pérez Castaña <juan.pérez.castaña@example.com>'
receivers = ['test1@example.com']
subject = 'A nice subject'
body = 'who cares'
message = buildmsg(sender, receivers, subject, body)
smtpObj.sendmail(sender, receivers, message.as_string())
但它正在抛出:
Traceback (most recent call last):
File "sendit.py", line 50, in <module>
smtpObj.sendmail(sender, receivers, message)
File "/usr/lib/python2.7/smtplib.py", line 722, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (555, '5.5.2 Syntax error. q17sm7358699wiv.10 - gsmtp', 'Juan P\xc3\xa9rez Casta\xc3\xb1a <juan.p\xc3\xa9rez.casta\xc3\xb1a@example.com>')
我没有得到的是我已经正确编码了标题,但它仍然拒绝它们。我想知道是否还需要对传递给smtpObj.sendmail
(sender
和receivers
) 的参数进行编码。如果是这样,我该怎么做?