本机已安装了支持 SMTP 的服务,可以直接smtplib.SMTP('localhost')。如果我们本机没有 sendmail 访问,也可以使用其他邮件服务商的 SMTP 访问(QQ、网易、Google等)。
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from data import emaildata def send_email(): smtpObj = smtplib.SMTP_SSL("xxx.xxx.xxx",xxx) #加密协议所以用STMP_SSL()而不是STMP() # message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message = MIMEMultipart() #发送附件用这个方法 recieve = emaildata.get_emaildata() message['From'] = Header('xxxxx@.com') #设置显示发件人的信息 message['To']= Header(recieve) #设置显示收件人的信息 subject = '中介系统接口自动化测试报告' message['Subject'] = Header(subject) #设置邮件主题 att1 = MIMEText(open("../report/report.html",'rb').read(),'base64','utf-8') #定义附件 att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="report.html"' message.attach(att1) #添加附件 message.attach(MIMEText("中介系统接口自动化测试报告")) #添加邮件正文 smtpObj.login('xxxx@.com','xxxxxxxxxx') #登录发件人的账号密码 smtpObj.sendmail("xxx@.com",recieve,message.as_string()) #发送邮件