"""
-------------------------------------------------
Project: Ai_codes
IDE Name: PyCharm
File Name: email_utils
Email: [email protected]
Author : 玖天
Date: 2018/11/13
Description :
-------------------------------------------------
Change Activity: 2018/11/13:
-------------------------------------------------
"""
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
smtpserver = 'smtp.163.com'
username = '[email protected]'
password = 'xxxx'
sender = '[email protected]'
class SendEmail():
def __init__(self, receiver, subject, ):
'''
初始化邮件发送对象
:param receiver: 收件人:list 类型-['[email protected]','[email protected]']
:param subject: 邮件标题
'''
self.receiver = receiver
self.msg = MIMEMultipart('mixed')
self.msg['Subject'] = subject
self.msg['From'] = '{} <{}>'.format(username, username)
self.msg['To'] = ";".join(receiver)
self.msg['Date'] = '{}'.format(datetime.datetime.now())
def add_text(self, text_plain):
'''
构造文字内容
:param text_plain: 字符串文件 可以使用回车换行等符号
:return:
'''
text_plain = MIMEText(text_plain, 'plain', 'utf-8')
self.msg.attach(text_plain)
def add_img(self, img_name, sendimagefile):
'''
发送图片
示例:
sendimagefile = open(img_path, 'rb').read()
send_img('ima_name',sendimagefile)
:param imgname: 图片路径
:return:
'''
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '')
image["Content-Disposition"] = 'attachment; filename="{}"'.format(img_name)
self.msg.attach(image)
def add_html(self, html):
'''
发送html
:param html: html文件
:return:
'''
text_html = MIMEText(html, 'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'
self.msg.attach(text_html)
def add_file(self, filename, sendfile):
'''
发送附件
调用示例:
sendfile = open(r'xxxx.xls', 'rb').read()
add_file('file_name',sendfile)
:param filename: 附件名称
:param sendfile: 附件文件
:return:
'''
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
text_att.add_header('Content-Disposition', 'attachment', filename=filename)
self.msg.attach(text_att)
def send(self):
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, self.receiver, self.msg.as_string())
smtp.quit()
if __name__ == '__main__':
em_obj = SendEmail(['[email protected]'],'测试邮件')
em_obj.add_text('测试邮件发送代码,无需回复')
em_obj.send()