工做中總有一些發送郵件的需求,雖然python提供了很好用的內置庫,可是每次都寫一遍很難受。經過總結經驗,寫了下面這個小工具,支持發送文本郵件、html郵件、還有能夠添加附件。再用到的時候只須要加到項目中,引用便可,或者能夠直接當一個腳本使用。html
1 # -*- coding:utf-8 -*- 2 """ 3 郵件發送小工具 4 """ 5 __author__ = "shu2015626" 6 7 import os 8 import smtplib 9 import logging 10 import datetime 11 import traceback 12 from typing import Dict, List, Sequence 13 from collections.abc import Iterable 14 from email.header import Header 15 from email.mime.text import MIMEText 16 from email.utils import formataddr, parseaddr 17 from email.mime.multipart import MIMEMultipart 18 from email.mime.application import MIMEApplication 19 20 import jinja2 21 22 logger = logging.getLogger('proj') 23 24 25 class EmailOper(object): 26 def __init__(self, email_host: str, email_port: int, email_sender: str, sender_pass: str, sender_alias: str = None): 27 """ 28 配置郵件發送服務 29 :param email_host: 發送郵件的主機 30 :param email_port: 郵件發送端口 31 :param email_sender: 發件人 32 :param sender_pass: 發件人密碼 33 :param sender_alias: 發件人別稱 34 """ 35 self.__email_host = email_host 36 self.__email_port = email_port 37 self.__email_sender = email_sender 38 self.__sender_pass = sender_pass 39 self.__sender_alias = sender_alias or self.__email_sender.split("@", 1)[0] 40 41 @property 42 def email_host(self): 43 return self.__email_host 44 45 @email_host.setter 46 def email_host(self, value: str): 47 self.__email_host = value 48 49 @property 50 def email_port(self): 51 return self.__email_port 52 53 @email_port.setter 54 def email_port(self, value: int): 55 self.__email_port = value 56 57 @property 58 def email_sender(self): 59 return self.__email_sender 60 61 @email_sender.setter 62 def email_sender(self, value: str): 63 self.__email_sender = value 64 65 @property 66 def sender_pass(self): 67 return self.__sender_pass 68 69 @sender_pass.setter 70 def sender_pass(self, value: str): 71 self.__sender_pass = value 72 73 @property 74 def sender_alias(self): 75 return self.__sender_alias 76 77 @sender_alias.setter 78 def sender_alias(self, value: str): 79 self.__sender_alias = value 80 81 def build_html_email(self, package_name: str, template_name: str, **context) -> str: 82 """ 83 用法同 flask.render_template: 84 85 build_html_email('package', 'template.html', var1='foo', var2='bar') 86 :param package_name: 87 :param template_name: 88 :param context: 89 :return: 90 """ 91 env = jinja2.Environment( 92 loader=jinja2.PackageLoader(package_name, 'templates') 93 ) 94 template = env.get_template(template_name) 95 96 return template.render(**context) 97 98 def __format_receivers(self, receivers: Sequence): 99 """ 100 格式化收件人的地址。