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()

复制代码

 最后把运行命令加入crontab中,就可以每天定时自动发送邮件了。

本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2010/09/28/1837578.html,如需转载请自行联系原作者

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C/C++内存泄漏及检测

2022-1-11 12:36:11

安全运维

Ubuntu安装docker

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索