发邮件功能 有很多种,我目前 使用的是python的smptlib 模块提供的发邮件功能,可以使用里面的SMTP对象的sendmail方法发邮件。
# -*- coding: utf-8 -*-
'''Created on 2018年1月4日@author: Susan
'''import smtplib
from email.mime.text import MIMEText#MIMEMultipart类用于实现多部分邮件的功能,缺省情况下它会创建Content-Type类型为mulitpart/mixed邮件。from email.mime.multipart import MIMEMultipartfrom email.header import Headerfrom time import sleep#新建一个邮件发送的类文件
class MailSender(object): #初始化登录邮箱准备发邮件 def __init__(self,smtp_server,username,pswd): self._username = username #创建邮件服务器对象 self.email_server =smtplib.SMTP() #连接smtp服务器 self.email_server.connect(smtp_server, 25) #登录邮箱self.email_server.login(self._username, pswd)
sleep(5)
#发送邮件(将需要发送给的邮件地址、邮件标题、内容、文件类型、文件名称封装到一起) def send(self, to_addr, subject, content, text_type='plain', attachment=None): if attachment == None: #创建发送邮件信息:包含创建对象 msg = MIMEText(content, text_type,'utf-8') #创建文件头内容 msg['Subject'] = Header(subject,'utf-8') #显示文件来是邮谁哪个邮箱发出的 msg['From'] = 'Susan<' + self._username + '>' #显示 发送到哪些地址 msg['To'] = to_addr elif isinstance(attachment, list): msg = MIMEMultipart() msg['Subject'] = Header(subject, 'utf-8') msg['From'] = 'Susan<' + self._username + '>' msg['To'] = to_addr # 构造附件1,传输E:\目录下的zy.txt文件 att = MIMEText(open(attachment, "rb").read(), 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = 'attachment; filename=%s'%attachment msg.attach( MIMEText(content, text_type, 'utf-8') ) msg.attach(att) elif isinstance(attachment, str): msg = MIMEMultipart() msg['Subject'] = Header(subject, 'utf-8') msg['From'] = 'Susan<' + self._username + '>' msg['To'] = to_addr #构造附件1,传输E:\目录下的zy.txt文件 att = MIMEText(open(attachment, "rb").read(), 'base64', 'utf-8') sleep(1) att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = 'attachment; filename=%s'%attachment msg.attach( MIMEText(content, text_type, 'utf-8') ) msg.attach(att) else: raise Exception, "attachment参数非法"
self.email_server.sendmail(self._username, to_addr, msg.as_string()) return def quit(self): # 结束SMTP会话 self.email_server.quit()#发送测试报告def send_test_report(report, subject, content, to_addrs): #将使用发邮件的邮箱服务器名称 、邮箱及密码传送给Mailsengder类进行初始化 ms = MailSender("smtp.sohu.com","xx@sohu.com","ssss") #如果是发送多个邮箱,就执行第一个条件,如果只有一个邮箱执行elif条件,否则就认为收件人参数格式不正确。 try: if isinstance(to_addrs, list): for to_addr in to_addrs: ms.send(to_addr, subject, content, "plain", report) elif isinstance(to_addrs, str): ms.send(to_addrs, subject, content, "plain", report) else: raise Exception, "收件人参数格式无效,必须是字符串类型" #发完邮件后退出发邮件系统 ms.quit() print (u"发送成功,请注意查收邮箱") except smtplib.SMTPException: print(u"Erro:发送邮件失败")if __name__ == '__main__': send_test_report("E:\\zy.txt","发邮件测试!",'对邮件封装后的测试!','sss@qq.com')
这个里面所注意的是:所发送的文件名称 尽量用英文,中文名称是python很多时候不兼容的。