使用smtplib發(fā)送郵件
def send_email(to_addrs,title,html_text='',mail_text='',enclosure='',cc_addrs=[]):
? ? ? ?# 發(fā)送者,標(biāo)題起便,html格式文本窖维,文本,附件陈辱,抄送,如果附件地址有中文需要解碼gbk
? ? ?if not to_addrs:
? ? ? ? ?to_addrs = cc_addrs
? ? ? ? cc_addrs = []
? mail_info = {
"from": '111111111@163.com',
"to": to_addrs,
"CC": cc_addrs,
"hostname": "smtp.163.com",
"username": '111111111@163.com',
"password": '123456',
"mail_subject":title,
"mail_text": mail_text,
"mail_encoding": "utf-8"
}
try:
smtp = SMTP_SSL(mail_info["hostname"])
except Exception as e:
logger.error(u'無法連接網(wǎng)絡(luò)或者郵箱服務(wù)器崩潰\n%s'%e)
return
# smtp.set_debuglevel(1)
smtp.ehlo(mail_info["hostname"])
smtp.login(mail_info["username"], mail_info["password"])
msg = MIMEMultipart('alternative')
msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"])
msg["from"] =? Header('郵件發(fā)送平臺','utf-8')
msg["to"] = ','.join(mail_info["to"])
msg["CC"] = ','.join(mail_info["CC"])
if html_text:
part2 = MIMEText(html_text, 'html', mail_info["mail_encoding"])
msg.attach(part2)
if mail_text:
part1 = MIMEText(mail_text, "plain", mail_info["mail_encoding"])
msg.attach(part1)
if enclosure:
part3 = MIMEApplication(open(enclosure,'rb').read())
part3.add_header('Content-Disposition', 'attachment', filename=os.path.split(enclosure)[1])
msg.attach(part3)
smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string())
smtp.quit()