import argparse
import smtplib, mimetypes
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email import utils
from email import encoders
from email.header import Header
import os.path
import datetime
import time
import sys
# import plugs.FileHelper as fileHelper
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
class SendMail():
startDate = ''
def __init__(self, reportDate):
startDate = reportDate
print('初始化SendMail邮件,值为:' + startDate)
def SendMethod(self, startDate=None):
print('SendMethod方法传参的值为:' + startDate)
# 发送邮箱服务器
smtpserver = 'mail.qq.com'
# smtpserver = 'smtp.163.com' 用smtplib.SMTP_SSL(smtpserver, 25)
# 发送邮箱用户名密码
user = 'test@qq.com'
password = 'test2018'
# 发送和接收邮箱
sender = 'test@qq.com'
receives = ['test@qq.com', 'test2@qq.com'] #
ccs = ['test@qq.com']
# 发送邮件主题和内容
subject = f'{startDate}_测试'
content = f' <p> 您好~ </p> <p>附件为{startDate}数据。</p><p> 请查收。 </p><p>谢谢~</p>' \
f'<br/><br/><br/><br/><p>From robot</>'
# 构造附件内容:定义附件,构造附件内容
_rarUrl = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))) + "\\test.zip"
print('附件地址是abspath:' + _rarUrl)
# _rarUrl2 = self.getsql(r"\test.rar")
# 构建发送与接收信息]
recc = receives + ccs
msgRoot = MIMEMultipart() # 发送附件的方法定义为一个变量
msgRoot.attach(MIMEText(content, 'html', 'UTF-8')) # 发送附件的方法中嵌套发送正文的方法
msgRoot['subject'] = subject
msgRoot['From'] = sender
msgRoot['To'] = ','.join(receives)
msgRoot['Cc'] = ','.join(ccs)
send_file = open(_rarUrl, 'rb').read() # 'rb'表示r读取,b表示二进制方式读取
att = MIMEText(send_file, 'base64', 'utf-8') # 调用传送附件模块,传送附件 send_file
#att = MIMEApplication(send_file) #用MIMEApplication 就不能有 base64和utf-8
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = f'attachment; filename={startDate}月测试.zip'
#att.add_header('Content-Disposition', 'attachment', filename=f'{startDate}月测试.zip')
msgRoot.attach(att) # 添加附件到正文中
print("Start 登录服务器.")
# SSL协议端口号要使用25
smtp = smtplib.SMTP(smtpserver, 25) # _SSL
print("Start 向服务器标识用户身份.")
# HELO 向服务器标识用户身份
smtp.helo(smtpserver)
print("Start 服务器返回结果确认.")
# 服务器返回结果确认
smtp.ehlo(smtpserver)
print("Start 登录邮箱服务器用户名和密码.")
try :
# 登录邮箱服务器用户名和密码
smtp.login(user, password)
print("Start send email...")
smtp.sendmail(sender, recc, msgRoot.as_string())
smtp.quit()
print("Send End!")
except smtplib.SMTPException as e:
print('error:',e) #打印错误