Send email,sendemail,#!/usr/bin/e
#!/usr/bin/env python# encoding: utf-8## filename: sendemail.py#import os.pathimport smtplibimport email.Headerimport email.MIMEMultipartimport email.MIMETextimport email.MIMEBaseimport email.Encodersimport mimetypesclass Email: def __init__(self, **kwg): self._setting = dict(kwg) def send(self, msg): smtp = smtplib.SMTP( self._setting.get('server'), self._setting.get('port', 25) ) msg["From"] = self._setting.get('From') smtp.sendmail( msg['From'], msg['To'].split(',')+ msg['Cc'].split(','), msg.as_string() ) smtp.quit()def writemail(coding='utf-8', **kwg): msg = email.MIMEMultipart.MIMEMultipart() msg["To"] = kwg.get('To', 'me@example.com') msg["Cc"] = kwg.get('Cc', '') msg['Date'] = email.Utils.formatdate() msg["Subject"] = email.Header.Header( kwg.get('Subject', 'No Subject'), coding) msg.attach(email.MIMEText.MIMEText( kwg.get('Context').encode(coding), _charset=coding)) return msgdef attach(msg, file_name): # 构造MIMEBase对象做为文件附件内容并附加到根容器 ctype, encoding = mimetypes.guess_type(file_name) if ctype is None or encoding is not None: ctype='application/octet-stream' maintype, subtype = ctype.split('/', 1) ## 读入文件内容并格式化 with open(file_name, 'rb') as data: file_msg = email.MIMEBase.MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) ## 设置附件头 basename = os.path.basename(file_name)E file_msg.add_header('Content-Disposition', 'attachment', filename = basename) email.Encoders.encode_base64(file_msg) msg.attach(file_msg) return msgdef _tester(): msg = writemail( To = 'someone@example.com', Subject = u'数据统计 [来自于运营部门]', Context = u'Please see the attachment.', ) attach(msg, u'../rpt/sys_monitor.zip') Email( server = 'smtp.163.com', From = 'someone@example.com' ).send(msg)if __name__ == '__main__': _tester()#该片段来自于http://byrx.net
评论关闭