使用 Python 发送带附件的 Email
关于 SMTP 的调试
http://wp.blkstone.me/2018/06/28/using-telnet-to-test-smtp-service/
代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/28 18:08
# @Author : BLKStone
# @Site : http://wp.blkstone.me
# @File : send_mail.py
# @Software: PyCharm
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 配置函数
def smtp_config():
# 生产环境
conf = {
'server': 'smtp.example.com',
'username': 'security@example.com',
'password': 'admin',
'sender_name': 'Nessus Scanbot',
'recipients': 'jack@exmaple.com,pony@exmaple.com',
'cc': 'alice@exmaple.com,bob@exmaple.com',
'body_text': "Hello, World!",
'report_location': 'D:\\work\\Webscan_906jpo.html'
}
return conf
# 发送结果报表邮件
# 参考资料
# https://www.youtube.com/watch?v=oc1EMINGL4I
# https://github.com/trln/relais-reports/blob/master/mail-aws.py
# https://stackoverflow.com/questions/8856117/how-to-send-email-to-multiple-recipients-using-python-smtplib
def build_email(conf):
print('build_email')
# conf = config.smtp_config()
d = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.today().strftime('%Y-%m-%d')
smtp_host = conf['server']
sender = conf['username']
sender_name = conf['sender_name']
recipient = conf['recipients']
cc = conf['cc']
report_location = conf['report_location']
subject = 'Nessus Bot Report ' + d
body_text = conf['body_text']
# 构造邮件头部
message = MIMEMultipart('alternative')
message['From'] = email.utils.formataddr((sender_name, sender))
# message['To'] = Header(recipient, 'utf-8')
message['To'] = recipient
message['Subject'] = Header(subject, 'utf-8')
message["Cc"] = cc
# 添加附件
file_stat = os.stat(report_location)
attachment_size = float(file_stat.st_size)/1024/1024 # 单位是 MB
# 邮件服务器管理员要求附件在 5M 以下
if attachment_size < 5:
report_file = open(report_location, 'r')
attachment = MIMEText(report_file.read(), _subtype="html", _charset="utf-8")
report_file.close()
attachment.add_header("Content-Disposition", "attachment",
filename="Nessus Report " + d2 + '.html')
message.attach(attachment)
else:
body_text = body_text + '\n由于报告文件较大,需要登陆 Nessus 扫描器查看。'
# 构造邮件正文
plain_text = MIMEText(body_text, 'plain', 'utf-8')
# 组装 邮件 MIME
message.attach(plain_text)
server = smtplib.SMTP(smtp_host)
server.set_debuglevel(1)
# 如果需要使用 SMTP over SSL
# server.starttls()
server.login(conf['username'], conf['password'])
server.sendmail(sender, message["To"].split(",") + message["Cc"].split(","), message.as_string())
server.close()
#######################################################################################################################
# 以下为测试函数
#######################################################################################################################
# 测试用例 1
def test_case_1():
conf = smtp_config()
build_email(conf)
# 主函数
if __name__ == '__main__':
test_case_1()
Leave a Reply