代码
import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def Send_Email(file_path,recevice_person,xianshi_person):
yesterday = datetime.today() + timedelta(-1)
yesterday_format = yesterday.strftime('%Y_%m_%d')
filename = yesterday_format + "_test.xlsx"
msg = MIMEMultipart()
msg["from"] = "data@xxxxx.com"
msg["to"] = xianshi_person
msg["subject"] = "xxxxxx"
txt = MIMEText("xxxxxx,xxxxxxxxxxxxxxxx(*^__^*) ", "plain", "utf-8")
msg.attach(txt)
# 构造附件
att = MIMEText(open(file_path,
"rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = "attachment; filename=%s" %filename
msg.attach(att)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect("smtp.mxhichina.com", "25")
state = smtpObj.login("data@xxxxxx.com", "Aaaaaaaa")
if state[0] == 235:
smtpObj.sendmail(msg["from"], recevice_person, msg.as_string())
print "邮件发送成功"
smtpObj.quit()
except smtplib.SMTPException, e:
print str(e)
xianshi_person="AA@xxxxxx.com,BB@xxxxxxx.com,CC@xxxxxx.com,DD@xxxxxxx.com"
recevice_person=["AA@xxxxxxxx.com","BB@xxxxx.com","CC@xxxxxxx.com","DD@xxxxxxx.com"]
遇到的坑:
折腾好久,邮件里可以看到收件人有多个,实际上始终只能第一个收件人可以收到邮件。经多次搜索,发现是这样:email中收件人和sendmail中的收件人是没啥联系的。
mail_to = ['test1@exp.com','test2@exp.com']
server = smtplib.SMTP()
server.connect()
server.sendmail(mail_from, mail_to, msg.as_string())
server.quit()
mail_to = 'test1@exp.com,test2@exp.com'
msg = MIMEMultipart('related') ##采用related定义内嵌资源的邮件体
msgtext = MIMEText(content,_subtype='html',_charset='utf-8') ##_subtype有plain,html等格式,避免使用错误
msg['Subject'] = subject
msg['From'] = mail_from
msg['To'] =mail_to
sendmail中收件人,它的格式应该为list。这个为实际的收件人地址。
而msg['To'] 格式是字符串(str)。这个只是为了邮件中打印出来而已。
sendmail查源码,python/lib/smtplib.py大概690行左右,或者搜索tolist。
网友评论