python邮件发送脚本
时间:2010-09-28 来源:Phinecos(洞庭散人)
代码
#!/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'] = "phinecos"
mailDict['password'] = "phinecos"
mailDict["from"] = "[email protected]"
mailDict["cc"] = "[email protected],[email protected]"
mailDict["to"] = "[email protected]"
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") or !paramMap.has_key("from") or !paramMap.has_key("to")):
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
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'] = "phinecos"
mailDict['password'] = "phinecos"
mailDict["from"] = "[email protected]"
mailDict["cc"] = "[email protected],[email protected]"
mailDict["to"] = "[email protected]"
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") or !paramMap.has_key("from") or !paramMap.has_key("to")):
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
smtp.sendmail(paramMap["from"], FinallyAdd, msgRoot.as_string())
smtp.quit()
return True
def process():
global mailDict
initMailConf()
sendMail(mailDict)
if __name__ == "__main__":
process()
相关阅读 更多 +