项目中用到的邮件发送模块,有发送附件功能
直接上代码:
-----------------------------------------
调用方法的代码,命名为main.py,需要注意的地方见代码上方的备注:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sendMail import *
if __name__ == '__main__':
# 发送方,必须为开通了smtp服务的邮箱账号,,否则无法通过程序发送邮件。怎么开通smtp服务,
#邮箱页面会有说明,我当时开通126是通过手机号进行验证后,就ok了
from_address='[email protected]'
# 发送方邮箱密码
from_pwd='flyTester123456'
# 发送方的smtp服务器,再次强调!!!想实现发送邮件功能,必须开通smtp服务!!!
from_smtp='smtp.126.com'
# 接收邮件列表,list形式,如['[email protected]','[email protected]','[email protected]']
mail_list=['[email protected]','[email protected]']
# 邮件标题
header='每时监控统计记录'
# 邮件正文,可以任意写内容
mail_body='本次统计记录,见附件'
# 附件路径,这次想将一个excel放到附件中发送
file='D:/mywork/data/2016-08-16.xlsx'
# 邮件中显示的附件名称,附件在邮件中以此名显示
filename='统计表.xlsx'
# 调用发送邮件模块,并接收返回值,此值包括了邮件是否发送成功,具体会返回什么,详见邮件发
#送模块
result=send_mail(file,filename,from_address,from_pwd,from_smtp,mail_list,header,mail_body)
# 打印返回值
print result
--------------------------------------------------------------------------------------------
发送邮件的代码,命名为sendMail.py,需要注意的地方见代码上方的备注:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from email.mime.text import MIMEText
from email.header import Header
from email import MIMEBase
from email import Encoders
from email import MIMEMultipart
import smtplib
# 定义发送邮件
def send_mail(file,filename,from_address,from_pwd,from_smtp,mail_list,header,mail_body):
try:
# 得到邮件实例
msg = MIMEMultipart.MIMEMultipart()
# ----------------------------------邮件正文-------------------------------
body = MIMEText(mail_body, 'html', 'utf-8')
msg.attach(body)
# ----------------------------------邮件标题-------------------------------
msg['Subject'] = Header(header,'utf-8')
# ----------------------------------发送者---------------------------------
msg['From'] = from_address
# ----------------------------------接收者,list列表形式,如
#['[email protected]','[email protected]','[email protected]']
msg['To'] = ";".join(mail_list)
# ----------------------------------添加附件-------------------------------
part = MIMEBase.MIMEBase('application', 'octet-stream')
part.set_payload(open(file, 'rb').read())
# 指定附件编码
Encoders.encode_base64(part)
# 附件在邮件中显示的名称
part.add_header('Content-Disposition', 'attachment; filename='+filename)
# 加入附件
msg.attach(part)
# -------------------------------- smtp服务器-----------------------------
smtp = smtplib.SMTP()
smtp.connect(from_smtp)
# ---------------------------------发送-----------------------------------
# 登录邮箱
smtp.login(from_address, from_pwd)
# 发送邮件
smtp.sendmail(from_address, mail_list, msg.as_string())
smtp.quit()
return 'email has send out !'
except Exception,e:
return 'send mail error !!! ',e
------------------------------------------------------------------------------------------------------------------------------------
更多请关注:FlyTester,关注技术的测试者
QQ群:456850134
web站:www.flytester.org
微信扫描二维码关注: