python邮件发送脚本
代码
#!/usr/bin/python
#coding=utf-8
#@author:dengyike
#@date:2010-09-28
#@version:1.0
#@description: auto sending email with attachment file
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
import logging
import sys
reload(sys)
sys.setdefaultencoding('utf8')
mailDict = {} #邮件配置信息
###################
#日志辅助类
#################
class Logger:
LOG_RELEASE= "releae"
LOG_RELEASE_FILE = "/tmp/pyMail.log"
def __init__(self, log_type):
self._logger = logging.getLogger(log_type)
if log_type == Logger.LOG_RELEASE:
self._logFile = Logger.LOG_RELEASE_FILE
handler = logging.FileHandler(self._logFile)
if log_type == Logger.LOG_RELEASE:
formatter = logging.Formatter('%(asctime)s ********* %(message)s')
else:
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
self._logger.addHandler(handler)
self._logger.setLevel(logging.INFO)
def log(self, msg):
if self._logger is not None:
self._logger.info(msg)
MyLogger = Logger(Logger.LOG_RELEASE) #Logger
def initMailConf():#初始化邮件配置信息
global mailDict
mailDict['server'] = "smtp.google.com"
mailDict['user'] = "dengyike"
mailDict['password'] = "dengyike"
mailDict["from"] = "dengyike@google.com"
mailDict["cc"] = "dengyike@google.com,phinecos@google.com"
mailDict["to"] = "dengyike@google.com"
mailDict["subject"] = "python邮件脚本测试"
mailDict["text"] = "这里是普通文本信息"
mailDict["html"] = '<font color = red ><b>这里是HTML文本信息</b></font>'
def sendMail(paramMap):#发送邮件
smtp = smtplib.SMTP()
msgRoot = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')
if paramMap.has_key("server") and paramMap.has_key("user") and paramMap.has_key("password"):
try:
smtp.set_debuglevel(1)
smtp.connect(paramMap["server"])
smtp.login(paramMap["user"], paramMap["password"])
except Exception, e:
MyLogger.log("smtp login exception!")
return False
else:
MyLogger.log("Parameters incomplete!")
return False
if paramMap.has_key("subject") == False or paramMap.has_key("from")== False or paramMap.has_key("to") == False:
MyLogger.log("Parameters incomplete!")
return False
msgRoot['subject'] = paramMap["subject"]
msgRoot['from'] = paramMap["from"]
if paramMap.has_key("cc"):
msgRoot['cc'] = paramMap["cc"]
msgRoot['to'] = paramMap["to"]
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgRoot.attach(msgAlternative)
TempAddTo = paramMap["to"]
if paramMap.has_key("text"):
msgText = MIMEText(paramMap["text"], 'plain', 'utf-8')
msgAlternative.attach(msgText)
if paramMap.has_key("html"):
msgText = MIMEText(paramMap["html"], 'html', 'utf-8')
msgAlternative.attach(msgText)
if paramMap.has_key("image"):
fp = open(paramMap["image"], 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>' )
msgRoot.attach(msgImage)
if paramMap.has_key("cc"):
TempAddTo = paramMap["to"] + "," + paramMap["cc"]
if TempAddTo.find(",") != -1:
FinallyAdd = TempAddTo.split(",")
else:
FinallyAdd = TempAddTo
#构造附件
fileName = "/tmp/test.zip"
basename = os.path.basename(fileName)
if os.path.exists(fileName): #数据文件存在
data = open(fileName, 'rb')
att = MIMEText(data.read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"' % basename
msgRoot.attach(att)
smtp.sendmail(paramMap["from"], FinallyAdd, msgRoot.as_string())
smtp.quit()
return True
def process():
global mailDict
initMailConf()
sendMail(mailDict)
if __name__ == "__main__":
process()
#coding=utf-8
#@author:dengyike
#@date:2010-09-28
#@version:1.0
#@description: auto sending email with attachment file
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
import logging
import sys
reload(sys)
sys.setdefaultencoding('utf8')
mailDict = {} #邮件配置信息
###################
#日志辅助类
#################
class Logger:
LOG_RELEASE= "releae"
LOG_RELEASE_FILE = "/tmp/pyMail.log"
def __init__(self, log_type):
self._logger = logging.getLogger(log_type)
if log_type == Logger.LOG_RELEASE:
self._logFile = Logger.LOG_RELEASE_FILE
handler = logging.FileHandler(self._logFile)
if log_type == Logger.LOG_RELEASE:
formatter = logging.Formatter('%(asctime)s ********* %(message)s')
else:
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
self._logger.addHandler(handler)
self._logger.setLevel(logging.INFO)
def log(self, msg):
if self._logger is not None:
self._logger.info(msg)
MyLogger = Logger(Logger.LOG_RELEASE) #Logger
def initMailConf():#初始化邮件配置信息
global mailDict
mailDict['server'] = "smtp.google.com"
mailDict['user'] = "dengyike"
mailDict['password'] = "dengyike"
mailDict["from"] = "dengyike@google.com"
mailDict["cc"] = "dengyike@google.com,phinecos@google.com"
mailDict["to"] = "dengyike@google.com"
mailDict["subject"] = "python邮件脚本测试"
mailDict["text"] = "这里是普通文本信息"
mailDict["html"] = '<font color = red ><b>这里是HTML文本信息</b></font>'
def sendMail(paramMap):#发送邮件
smtp = smtplib.SMTP()
msgRoot = MIMEMultipart('related')
msgAlternative = MIMEMultipart('alternative')
if paramMap.has_key("server") and paramMap.has_key("user") and paramMap.has_key("password"):
try:
smtp.set_debuglevel(1)
smtp.connect(paramMap["server"])
smtp.login(paramMap["user"], paramMap["password"])
except Exception, e:
MyLogger.log("smtp login exception!")
return False
else:
MyLogger.log("Parameters incomplete!")
return False
if paramMap.has_key("subject") == False or paramMap.has_key("from")== False or paramMap.has_key("to") == False:
MyLogger.log("Parameters incomplete!")
return False
msgRoot['subject'] = paramMap["subject"]
msgRoot['from'] = paramMap["from"]
if paramMap.has_key("cc"):
msgRoot['cc'] = paramMap["cc"]
msgRoot['to'] = paramMap["to"]
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgRoot.attach(msgAlternative)
TempAddTo = paramMap["to"]
if paramMap.has_key("text"):
msgText = MIMEText(paramMap["text"], 'plain', 'utf-8')
msgAlternative.attach(msgText)
if paramMap.has_key("html"):
msgText = MIMEText(paramMap["html"], 'html', 'utf-8')
msgAlternative.attach(msgText)
if paramMap.has_key("image"):
fp = open(paramMap["image"], 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>' )
msgRoot.attach(msgImage)
if paramMap.has_key("cc"):
TempAddTo = paramMap["to"] + "," + paramMap["cc"]
if TempAddTo.find(",") != -1:
FinallyAdd = TempAddTo.split(",")
else:
FinallyAdd = TempAddTo
#构造附件
fileName = "/tmp/test.zip"
basename = os.path.basename(fileName)
if os.path.exists(fileName): #数据文件存在
data = open(fileName, 'rb')
att = MIMEText(data.read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"' % basename
msgRoot.attach(att)
smtp.sendmail(paramMap["from"], FinallyAdd, msgRoot.as_string())
smtp.quit()
return True
def process():
global mailDict
initMailConf()
sendMail(mailDict)
if __name__ == "__main__":
process()
最后把运行命令加入crontab中,就可以每天定时自动发送邮件了。
作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2010-09-28 15:02 Phinecos(洞庭散人) 阅读(3183) 评论(0) 编辑 收藏 举报