好久不写博客了,发现工作中常用的功能还是还要总结记录的,不然下次遇到又要重新写一遍,重复造轮子真的很浪费时间。扯多了,上代码…
代码示例
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging
class MailConf(object):
HOST = 'smtp.163.com' # 邮件服务器地址
USER = 'aaa@163.com' # 用户
PASSWORD = '12345678' # 授权码
SENDER = 'erty@163.com' # 发送者
RECEIVERS = ['wertyu@163.com'] # 接受者列表
SUBJECT = "这是主题呀!!!" # 主题
class Mail(object):
def __init__(self):
self.mail_host = MailConf.HOST
self.mail_user = MailConf.USER
self.mail_pass = MailConf.PASSWORD
self.SMTP = None
def __enter__(self):
logging.info("连接SMTP")
self.SMTP = smtplib.SMTP()
self.SMTP.connect(self.mail_host, 25)
self.SMTP.login(self.mail_user, self.mail_pass)
return self
def send(self, sender=None, receivers=None, subject=None, content=None, attaches=None):
"""
功能:发送邮件
:param sender: 发送者 'haha@163.com'
:param receivers: 接受者列表 ['haha@163.com', 'hehe@163.com', ...]
:param subject: 主题 subject
:param content: 内容 {"content": "邮件测试111", "format": "plain/html"}
:param attaches: 附件列表 [{"path": "./", "file_name": "test.xls"}, ...]
:return: Failed/Success
"""
logging.info("发送邮件 start ...")
message = MIMEMultipart()
message['From'] = sender
if receivers and isinstance(receivers, list):
receiver_str = ",".join(receivers)
else:
receiver_str = receivers
message['To'] = receiver_str
message['Subject'] = subject
part1 = MIMEText(content.get("content"), content.get("format"), 'utf-8')
message.attach(part1)
for attach in attaches:
# with open(attach.get("path") + attach.get("file_name"), "rb") as f:
# cont = f.read()
file = attach.get("path") + attach.get("file_name")
part2 = MIMEText(open(file, "rb").read(), 'base64', 'utf-8')
# 附件设置内容类型,方便起见,设置为二进制流
part2['Content-Type'] = 'application/octet-stream'
# 设置附件头,添加文件名
part2['Content-Disposition'] = 'attachment;filename="{}"'.format(attach.get("file_name")) # 注意:附件名必须为英文
message.attach(part2)
try:
self.SMTP.sendmail(sender, receivers, message.as_string())
except smtplib.SMTPException as e:
logging.error("发送邮件失败:{}".format(e))
return "Failed"
logging.info("发送邮件 end")
return "Success"
def __exit__(self, exc_type, exc_val, exc_tb):
logging.info('断开连接')
self.SMTP.quit()
# with Mail() as M:
# ret = M.send(
# sender=MailConf.SENDER,
# receivers=MailConf.RECEIVERS,
# subject=MailConf.SUBJECT,
# content={
# "content": "邮件测试111",
# "format": "plain"
# },
# attaches=[
# {
# "path": "./",
# "file_name": "test.xls"
# }
# ]
# )
# print(ret)
上下文管理器
Python中的上下文管理器能帮我们自动创建和释放资源,我们可以专注于要实现的功能本身
如果想了解更多关于上下文内容可以看这篇文章:Python上下文管理器