python 发邮件
邮件内容支持附件、图片、文字
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/13 6:05 下午
# @Author : 陈日志
# @Email : [email protected]
# @File : Mail.py
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
class Mail(object):
def __init__(self, smtp_server, smtp_port=25, ssl=False):
self._message = MIMEMultipart()
if ssl:
self.smtp = smtplib.SMTP_SSL(smtp_server, 465 if smtp_port == 25 else smtp_port)
else:
self.smtp = smtplib.SMTP(smtp_server, smtp_port)
self._receivers = None
self._sender = None
self._content = ''
self._imageid = 0
def login(self, user, password):
try:
self.smtp.login(user, password)
except Exception as e:
print(e)
raise smtplib.SMTPAuthenticationError(1, "login failed")
self._message["From"] = user
self._sender = user
@property
def receives(self):
return self._receivers
@property
def receives(self):
return self._receivers
@receives.setter
def receives(self, receivers):
type_ = type(receivers)
if type_ is str:
receivers = receivers.split(',')
self._message["To"] = receivers
self._receivers = receivers
elif type_ is list or type_ is tuple:
self._message["To"] = ','.join(receivers)
self._receivers = receivers
@property
def title(self):
return self._message.get("Subject")
@title.setter
def title(self, title):
self._message["Subject"] = Header(title, 'utf-8')
@property
def content(self):
return self._message
@content.setter
def content(self, content):
self._content = content
@property
def imageid(self):
self._imageid += 1
return self._imageid
def append_content(self, content):
self._content += content
def add_attachment(self, file):
att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
# att["Content-Disposition"] = 'attachment; filename=%s' % os.path.basename(file).encode('utf-8')
att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', os.path.basename(file)))
self._message.attach(att)
def add_image(self, img):
imageid = 'image%s' % self.imageid
msg = MIMEImage(open(img, 'rb').read())
msg.add_header('Content-ID', imageid)
self._content += '<br/><img src="cid:%s">' % imageid
self._message.attach(msg)
def send(self):
self._message.attach(MIMEText(self._content, 'html', 'utf-8'))
try:
self.smtp.sendmail(self._sender, self._receivers, self._message.as_string())
except Exception as e:
print(e)
raise smtplib.SMTPConnectError(1, "Send mail error")
def logout(self):
self.smtp.quit()