业务中有自动发送邮件的需求,目前还没有做添加附件的功能。
同时,也解决了邮件中中文乱码的情况。
直接上代码:
import smtplib from email.mime.text import MIMEText
def mail_send(title, body): host = "smtp.163.com" port = 465 sender = "xxx@163.com" pwd = "1234" receiver = ["aaa@163.com", "bbb@163.com"] # 设置邮件信息 msg = MIMEText(body, 'html', 'utf-8') # 正文utf8 msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" msg['subject'] = title if isinstance(title, unicode) else unicode(title.decode("utf8")) # title必须为unicode编码 msg['from'] = sender msg['to'] = ",".join(receiver) s = smtplib.SMTP_SSL(host, port) s.login(sender, pwd) s.sendmail(sender, receiver, msg.as_string()) print 'The mail named %s to %s is sended successly.' % (title, receiver)