由于工作中经常需要收发电子邮件,例如每日(周)的工作报告,测试报告,监控告警,定时提醒等等,大都已电子邮件的形式发送。本文将实现一个 Python 的电子邮件发送类,支持发送多个附件(目录),HTML或纯文本内容,抄送收件人,多个接收者等功能。
代码实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2015 By Thomas Hu. All rights reserved.
@author : Thomas Hu
@version: 1.0
@created: 2015-05-17
'''
import base64
import httplib
import re
import os
import smtplib
from xml.etree import ElementTree
from email.utils import formatdate
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email import Encoders
class EmailSender(object):
def __init__(self, smtp_server, smtp_port=0, verbose=False, debug_level=1, encoding="utf-8"):
''' Initiate the EmailSender.
@param smtp_server: the Email SMTP server.
@param smtp_port: the Email SMTP server port, if use the default port(25), you can set it to 0 or 25.
@param verbose: show the processing information if set to 'True', default is 'False'.
@param debug_level: set the smtplib debug level, if it's '0', will enable debug information.
@param encoding: the encoding or charset for email body text or attachment file name, default is "utf-8".
'''
self.server = smtp_server
self.port = int(smtp_port)
self.verbose = verbose
self.debug_level = int(debug_level)
self.encoding = encoding
self.attachments = []
#Create smtp instance
self.smtp = smtplib.SMTP(self.server, self.port)
self.smtp.set_debuglevel(self.debug_level)
self.pr