###背景
最近在做监控时需要使用smtp发送群邮件,但使用python smtp时遇到一个很坑的地方,刚刚越过,所以记录一下
直接上代码:
def send_mail(server, fro, to, subject, text, files=[]):
assert type(server) == dict
assert type(files) == list
msg = MIMEMultipart()
msg['From'] = fro
msg['Subject'] = subject
msg['To'] = to //注意这里,不是要发的用户,只是在邮件中显示的收件人信息
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text,'html','utf-8'))
msg["Accept-Language"]="zh-CN"
msg["Accept-Charset"]="ISO-8859-1,utf-8"
for file in files:
part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
part.set_payload(open(file, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part)
import smtplib
smtp = smtplib.SMTP(server['name'])
smtp.login(server['user'], server['passwd'])
to = to.strip(',').split(',') //注意这里,用的是用户列表而不是字符串,这里是真正的用户列表
smtp.sendmail(fro, to, msg.as_string())
smtp.close()
查明原因如下:
The problem is that SMTP.sendmail and email.MIMEText need two different things.
email.MIMEText sets up the “To:” header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)
SMTP.sendmail, on the other hand, sets up the “envelope” of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.
So, what you need to do is COMBINE the two replies you received. Set msg‘To’ to a single string, but pass the raw list to sendmail.