# 发送邮件
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
from conf import setting
def mail_smtp_string(subject,msg):
from_addr = setting.MAIL_USER # 输入Email地址和口令:
password = setting.MAIL_PASSWRD
smtp_server = setting.MAIL_HOST # 输入SMTP服务器地址:
to_addr = setting.TO # 输入收件人地址:
for a in to_addr:
msg['To'] = Header(a)
msg['From'] = Header(from_addr)
msg['subject'] = Header(subject)
server = smtplib.SMTP_SSL(host='smtp.gmail.com').connect(host='smtp.gmail.com', port=465)
server.connect(smtp_server, 465)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string()) # as_string()把MIMEText对象msg变成str
server.quit()
def mail_smtp_attrs(subject,file_name,result=None,attrs=None):
from_addr = setting.MAIL_USER # 输入Email地址和口令:
password = setting.MAIL_PASSWRD
smtp_server = setting.MAIL_HOST # 输入SMTP服务器地址:
to_addr = setting.TO # 输入收件人地址:
msg = MIMEMultipart()
msg.attach(MIMEText('本次监控结果如下:
%s' % result, 'plain', 'utf-8')) # 发送文本内容
for a in to_addr:
msg['To'] = Header(a)
msg['From'] = Header(from_addr)
msg['subject'] = Header(subject)
att3 = MIMEText(open(attrs, 'rb').read(), 'base64', 'utf-8')
att3["Content-Type"] = 'application/octet-stream'
att3.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(att3)
server = smtplib.SMTP_SSL(host=smtp_server,port=465)
server.connect(host=smtp_server, port=465)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string()) # as_string()把MIMEText对象msg变成str
server.quit()