#coding=utf-8
# #!/usr/bin/python3
# @author zouwh
# @date 2020-10-29
# python推送邮件代码库
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from datetime import datetime, timedelta
import sys
my_sender = 'xxx@xxx.com' # 发件人邮箱账号
my_pass = 'xxx' # 发件人邮箱密码
subject = "邮件推送报表信息" # 邮件的主题
def send_mail(context, filename1=None):
my_user = email_arr
print("my_user: " + ",".join(my_user))
m = MIMEMultipart()
m['From'] = formataddr(["python推送邮件测试", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
m['To'] = formataddr(["人员", ','.join(my_user)]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
m['Subject'] = subject
m.attach(context)
# 添加附件
if filename1 is not None:
attachment = MIMEApplication(open(filename1, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '音乐类型及特点.csv'))
m.attach(attachment)
try:
server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) # 发件人邮箱中的SMTP服务器
server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(my_sender, my_user, m.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
return True
except Exception as e:
print(e)
return False
if __name__ == '__main__':
email_str = "xxx@xxx.com"
email_arr = email_str.split(',')
filename1 = sys.argv[1]
print("email_str: " + email_str)
html = """<font size="3">邮件附件推送音乐类型及特点<br>"""
context = MIMEText(html, _subtype='html', _charset='utf-8')
if send_mail(context,filename1):
print("发送成功")
else:
print("发送失败")
效果: