python邮件发送脚本
转自: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邮件发送脚本的更多相关文章
- centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)
centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) ##################### sendmail.py begin ######## ...
- Python邮件发送脚本(Linux,Windows)通用
脚本 #!/usr/bin/python #-*- coding:utf-8 -*- #Python Mail for chenglee #if fileformat=dos, update file ...
- python 邮件发送 脚本
import smtplib from email.header import Header from email.mime.text import MIMEText from_addr = 'XXX ...
- Python 邮件发送
python发送各类邮件的主要方法 python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点. 一.相关模块介绍 ...
- python邮件发送
'''qq邮件与其他邮件有所不同,下以我的qq邮件为例(切勿转载):''' import osimport smtplibfrom email.mime.text import MIMEText # ...
- Python邮件发送源码
-- coding:utf-8 -- i = 0 while i < 10: #发送十次 import smtplib from email.mime.text import MIMEText ...
- python邮件发送自动化测试报告
话不多说直接贴代码 # encoding: utf-8import smtplib #发送邮件模块from email.mime.text import MIMEText #邮件内容from emai ...
- python邮件发送:普通文本、html、添加附件
# -*- coding: utf-8 -*- # @Time : 2019/9/19 13:46 # @Author : HuangWenjun # @Email : 350920551@qq.co ...
- 一个python的邮件发送脚本,自动,定时,可以附件发送,抄送,附有说明文件
#!/bin/env python # -*- coding: utf-8 -*- import datetime import smtplib import os,sys from email.mi ...
随机推荐
- Traveling
Problem J: Traveling Time Limit: 1 Sec Memory Limit: 32 MB Description SH likes traveling around th ...
- C++设计模式之建造模式
#include <iostream>using namespace std; class ApplePhone { public: virtual void buildCamera()= ...
- SymPy-符号运算好帮手
SymPy-符号运算好帮手 SymPy是Python的数学符号计算库,用它可以进行数学公式的符号推导.为了调用方便,下面所有的实例程序都假设事先从sympy库导入了所有内容: >>> ...
- spring mvc 建立下拉框并进行验证demo
原文出处:http://howtodoinjava.com/spring/spring-mvc/spring-mvc-populate-and-validate-dropdown-example/ 该 ...
- 修改spinner选中以后显示的字体颜色
原来spinner选中以后显示的view 还是textview ,这样就是可以设置它的字体颜色了 sp.setOnItemSelectedListener(new OnItemSelectedLi ...
- c_str()
1.string类成员函数c_str()的原型: const char *c_str()const;//返回一个以null终止的c字符串 2.c_str()函数返回一个指向正规c字符串的指针,内容和s ...
- SlidingMenu的编译及使用
1. 在github上有一个效果不错的开源库,SlidingMenu 最新的代码下载下来后,ExampleListActivity项目会报错: No resource found that ...
- 自学JQuery Mobile的几个例子
JQuery Mobile是一个用于构建移动Web应用程序的框架,适用于主流的移动设备(智能手机.平板电脑),该框架利用了HTML5和CSS3技术减少了额外的脚本文件的编写.具体JQuery Mobi ...
- UITextField键盘类型
UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)]; //初始化textfield并 ...
- 在VC中,为图片按钮添加一些功能提示(转)
在VC中,也常常为一些图片按钮添加一些功能提示.下面讲解实现过程:该功能的实现主要是用CToolTipCtrl类.该类在VC msdn中有详细说明.首先在对话框的头文件中加入初始化语句:public ...