转自:http://phinecos.cnblogs.com/
1 #!/usr/bin/python 2 #coding=utf-8 3 4 #@author:dengyike 5 #@date:2010-09-28 6 #@version:1.0 7 #@description: auto sending email with attachment file 8 9 import email 10 import mimetypes 11 from email.MIMEMultipart import MIMEMultipart 12 from email.MIMEText import MIMEText 13 from email.MIMEImage import MIMEImage 14 import smtplib 15 import logging 16 import sys 17 18 reload(sys) 19 sys.setdefaultencoding('utf8') 20 21 mailDict = {} #邮件配置信息 22 23 ################### 24 #日志辅助类 25 ################# 26 class Logger: 27 LOG_RELEASE= "releae" 28 LOG_RELEASE_FILE = "/tmp/pyMail.log" 29 30 def __init__(self, log_type): 31 self._logger = logging.getLogger(log_type) 32 if log_type == Logger.LOG_RELEASE: 33 self._logFile = Logger.LOG_RELEASE_FILE 34 handler = logging.FileHandler(self._logFile) 35 if log_type == Logger.LOG_RELEASE: 36 formatter = logging.Formatter('%(asctime)s ********* %(message)s') 37 else: 38 formatter = logging.Formatter('%(message)s') 39 handler.setFormatter(formatter) 40 self._logger.addHandler(handler) 41 self._logger.setLevel(logging.INFO) 42 43 def log(self, msg): 44 if self._logger is not None: 45 self._logger.info(msg) 46 47 MyLogger = Logger(Logger.LOG_RELEASE) #Logger 48 49 def initMailConf():#初始化邮件配置信息 50 global mailDict 51 mailDict['server'] = "smtp.google.com" 52 mailDict['user'] = "dengyike" 53 mailDict['password'] = "dengyike" 54 mailDict["from"] = "dengyike@google.com" 55 mailDict["cc"] = "dengyike@google.com,phinecos@google.com" 56 mailDict["to"] = "dengyike@google.com" 57 mailDict["subject"] = "python邮件脚本测试" 58 mailDict["text"] = "这里是普通文本信息" 59 mailDict["html"] = '<font color = red ><b>这里是HTML文本信息</b></font>' 60 61 def sendMail(paramMap):#发送邮件 62 smtp = smtplib.SMTP() 63 msgRoot = MIMEMultipart('related') 64 msgAlternative = MIMEMultipart('alternative') 65 if paramMap.has_key("server") and paramMap.has_key("user") and paramMap.has_key("password"): 66 try: 67 smtp.set_debuglevel(1) 68 smtp.connect(paramMap["server"]) 69 smtp.login(paramMap["user"], paramMap["password"]) 70 except Exception, e: 71 MyLogger.log("smtp login exception!") 72 return False 73 else: 74 MyLogger.log("Parameters incomplete!") 75 return False 76 77 if paramMap.has_key("subject") == False or paramMap.has_key("from")== False or paramMap.has_key("to") == False: 78 MyLogger.log("Parameters incomplete!") 79 return False 80 msgRoot['subject'] = paramMap["subject"] 81 msgRoot['from'] = paramMap["from"] 82 if paramMap.has_key("cc"): 83 msgRoot['cc'] = paramMap["cc"] 84 msgRoot['to'] = paramMap["to"] 85 msgRoot.preamble = 'This is a multi-part message in MIME format.' 86 msgRoot.attach(msgAlternative) 87 TempAddTo = paramMap["to"] 88 if paramMap.has_key("text"): 89 msgText = MIMEText(paramMap["text"], 'plain', 'utf-8') 90 msgAlternative.attach(msgText) 91 if paramMap.has_key("html"): 92 msgText = MIMEText(paramMap["html"], 'html', 'utf-8') 93 msgAlternative.attach(msgText) 94 if paramMap.has_key("image"): 95 fp = open(paramMap["image"], 'rb') 96 msgImage = MIMEImage(fp.read()) 97 fp.close() 98 msgImage.add_header('Content-ID', '<image1>' ) 99 msgRoot.attach(msgImage) 100 if paramMap.has_key("cc"): 101 TempAddTo = paramMap["to"] + "," + paramMap["cc"] 102 if TempAddTo.find(",") != -1: 103 FinallyAdd = TempAddTo.split(",") 104 else: 105 FinallyAdd = TempAddTo 106 107 #构造附件 108 fileName = "/tmp/test.zip" 109 basename = os.path.basename(fileName) 110 if os.path.exists(fileName): #数据文件存在 111 data = open(fileName, 'rb') 112 att = MIMEText(data.read(), 'base64', 'gb2312') 113 att["Content-Type"] = 'application/octet-stream' 114 att["Content-Disposition"] = 'attachment; filename="%s"' % basename 115 msgRoot.attach(att) 116 smtp.sendmail(paramMap["from"], FinallyAdd, msgRoot.as_string()) 117 smtp.quit() 118 return True 119 120 def process(): 121 global mailDict 122 initMailConf() 123 sendMail(mailDict) 124 125 if __name__ == "__main__": 126 process()
最后把运行命令加入crontab中,就可以每天定时自动发送邮件了。
时间: 2024-10-26 06:07:10