转自:http://phinecos.cnblogs.com/

 #!/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中,就可以每天定时自动发送邮件了。

python邮件发送脚本的更多相关文章

  1. centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)

    centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) #####################     sendmail.py  begin     ######## ...

  2. Python邮件发送脚本(Linux,Windows)通用

    脚本 #!/usr/bin/python #-*- coding:utf-8 -*- #Python Mail for chenglee #if fileformat=dos, update file ...

  3. python 邮件发送 脚本

    import smtplib from email.header import Header from email.mime.text import MIMEText from_addr = 'XXX ...

  4. Python 邮件发送

    python发送各类邮件的主要方法   python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点.     一.相关模块介绍 ...

  5. python邮件发送

    '''qq邮件与其他邮件有所不同,下以我的qq邮件为例(切勿转载):''' import osimport smtplibfrom email.mime.text import MIMEText # ...

  6. Python邮件发送源码

    -- coding:utf-8 -- i = 0 while i < 10: #发送十次 import smtplib from email.mime.text import MIMEText ...

  7. python邮件发送自动化测试报告

    话不多说直接贴代码 # encoding: utf-8import smtplib #发送邮件模块from email.mime.text import MIMEText #邮件内容from emai ...

  8. python邮件发送:普通文本、html、添加附件

    # -*- coding: utf-8 -*- # @Time : 2019/9/19 13:46 # @Author : HuangWenjun # @Email : 350920551@qq.co ...

  9. 一个python的邮件发送脚本,自动,定时,可以附件发送,抄送,附有说明文件

    #!/bin/env python # -*- coding: utf-8 -*- import datetime import smtplib import os,sys from email.mi ...

随机推荐

  1. C语言struct类型

    在实际问题中,一组数据往往具有不同的数据类型.例如, 在学生登记表中,姓名应为字符型:学号可为整型或字符型: 年龄应为整型:性别应为字符型:成绩可为整型或实型. 显然不能用一个数组来存放这一组数据. ...

  2. php命名空间使用

    对于命名空间,官方文档已经说得很详细[查看],我在这里做了一下实践和总结. 命名空间一个最明确的目的就是解决重名问题,PHP中不允许两个函数或者类出现相同的名字,否则会产生一个致命的错误.这种情况下只 ...

  3. idea破解码

    43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...

  4. 字符编码和python使用encode,decode转换utf-8, gbk, gb2312

    ASCII码 标准ASCII码使用7位二进制数表示大写或小写字母,数字0到9标点符号以及在美式英语中使用的特殊控制字符. 在标准ASCII码中,最高位(b7)用作奇偶校验位,所谓奇偶校验,是指在代码传 ...

  5. [Leetcode][Python]24: Swap Nodes in Pairs

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 24: Swap Nodes in Pairshttps://oj.leetc ...

  6. AspectJ AOP例子

    最近在学习Spring AOP,其中涉及到AspectJ的AOP框架.主要参考:http://howtodoinjava.com/spring/spring-aop/spring-aop-aspect ...

  7. 【POJ】2492 A bug's life ——种类并查集

    A Bug's Life Time Limit: 10000MS   Memory Limit: 65536K Total Submissions: 28211   Accepted: 9177 De ...

  8. linux下各种代理的设置

    http://los-vmm.sc.intel.com/wiki/OpenStack_New_Hire_Guide#Apply_JIRA_account Set up your proxy. The ...

  9. 在线词典php

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. Android 常用开发类库

    android.app :提供高层的程序模型.提供基本的运行环境    android.content :包含各种的对设备上的数据进行访问和发布的类    android.database :通过内容 ...