Python 发邮件
普通邮件
[root@localhost checksalt]# cat python_email.py
#!/usr/bin/Python
# -*- coding: utf-8 -*-
import sys
def smtp(title,file):
import smtplib
from email.mime.text import MIMEText
from email.header import Header
with open(file, 'r') as f:
content = f.read()
#加邮件头
msg=MIMEText(content,'plain', 'utf-8')
to_list=['XXX1@qq.com',XXX2@qq.com]
msg['from'] = 'XXX@qq.com'
msg['subject'] = title
#发送邮件
try:
server = smtplib.SMTP()
server.connect('smtp.exmail.qq.com')
server.login('XXX@qq.com','xxxxx')#XXX为用户名,xxxxx为密码
server.sendmail(msg['from'],to_list,msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e)
if __name__ == '__main__':
smtp(sys.argv[1],sys.argv[2])
[root@localhost checksalt]#
带附件邮件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
oneday = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = datetime.date.today() - oneday
yesterday_time = datetime.datetime.strftime(yesterday, '%Y-%m-%d')
sender = 'xxxx_xxxx@xxxx.com' ##发送者
receivers = ['xxxx@xxxx.com','xxxx@xxxx.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("来源", 'utf-8')
message['To'] = Header("目的", 'utf-8')
subject = 'xxxx日志'
message['Subject'] = Header(subject, 'utf-8')
#邮件正文内容
message.attach(MIMEText('%sxxxx日志信息,请看附件!!'% yesterday_time, 'plain', 'utf-8'))
# 构造附件,传送当前目录下的 test.txt 文件
try:
file = 'file.log.%s' % yesterday_time
print file
att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = "p_w_upload; filename=extProfile.log.%s" %yesterday_time
message.attach(att1)
smtpObj = smtplib.SMTP()
smtpObj.connect('smtp.exmail.qq.com')
smtpObj.login('xxxx_xxxx@xxxx.com', 'xxxxxxxxxxxx') # XXX为用户名,XXXXX为密码
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print "邮件发送成功"
except smtplib.SMTPException as e :
print str(e)
print "Error: 无法发送邮件"
except IOError as e:
print str(e)
print "Error: 无法发送邮件"
普通格式邮件
#!/usr/bin/env python
#_*_coding:utf-8 _*_
__author__ = 'gaogd'
import smtplib
import string
'''
实现图文格式的服务器性能报表邮件
'''
HOST = "smtp.exmail.qq.com" #定义smtp主机
SUBJECT = "Test email from Python" #定义邮件主题
TO = "xxx@xxx.com" #定义邮件收件人
FROM = "xxx@xxx.com" #定义邮件发件人
text = "Python rules them all!" #邮件内容
BODY = string.join(( #组装sendmail方法的邮件主体内容,各段以"\r\n"进行分隔
"From: %s" % FROM,
"To: %s" % TO,
"Subject:%s" % SUBJECT,
"",
text
),"\r\n")
server = smtplib.SMTP() #创建一个SMTP()对象
server.connect(HOST,"25") #通过connect方法连接smtp主机
server.starttls() #启动安全传输模式
server.login("xx@xxx.com", "xxxxx") # 邮箱账号登录校验
server.sendmail(FROM,[TO],BODY)#邮件发送
server.quit() #断开smtp连接
print 'send ok'
Html格式邮件
#!/usr/bin/env python
#_*_coding:utf-8 _*_
__author__ = 'gaogd'
import smtplib
from email.mime.text import MIMEText #导入MIMEText类
HOST = "smtp.exmail.qq.com" #定义smtp主机
SUBJECT = u"官网流量数据报表" #定义邮件主题
TO = "xxx@xxx.com" #定义邮件收件人
FROM = "xxx@xxx.com" #定义邮件发件人
'''
实现html的服务器性能报表邮件
'''
msg = MIMEText("""
#创建一个MIMEText对象,分别指定HTML内容、类型(文本或html)、字符编码
<table width="800" border="0" cellspacing="0" cellpadding="4">
<tr>
<td bGColor="#CECFAD" height="20"duokan-code-cn">">*官网数据
<a href="monitor.domain.com">更多>></a></td>
</tr>
<tr>
<td bgcolor="#EFEBDE" height="100"duokan-code-cn">">
1)日访问量:<font color=red>152433</font> 访问次数:23651 页面浏览量:
45123 点击数:545122 数据流量:504Mb<br>
2)状态码信息<br>
500:105 404:3264 503:214<br>
3)访客浏览器信息<br>
IE:50% firefox:10% chrome:30% other:10%<br>
4)页面信息<br>
/index.PHP 42153<br>
/view.php 21451<br>
/login.php 5112<br>
</td>
</tr>
</table>
""","html","utf-8")
msg['Subject'] = SUBJECT #邮件主题
msg['From']=FROM #邮件发件人,邮件头部可见
msg['To']=TO #邮件收件人,邮件头部可见
try:
server = smtplib.SMTP() #创建一个SMTP()对象
server.connect(HOST,"25") #通过connect方法连接smtp主机
server.starttls() #启动安全传输模式
server.login("xx@xxx.com", "xxxxx") # 邮箱账号登录校验
server.sendmail(FROM, TO, msg.as_string()) #邮件发送
server.quit() #断开smtp连接
print "邮件发送成功!"
except Exception as e:
print "失败:"+str(e)
图片格式邮件
#!/usr/bin/env python
#_*_coding:utf-8 _*_
__author__ = 'gaogd'
import smtplib
from email.mime.multipart import MIMEMultipart #导入MIMEMultipart类
from email.mime.text import MIMEText #导入MIMEText类
from email.mime.p_w_picpath import MIMEImage #导入MIMEImage类
HOST = "smtp.exmail.qq.com" #定义smtp主机
SUBJECT = u"业务性能数据报表" #定义邮件主题
TO = "xxx@xxx.com" #定义邮件收件人
FROM = "xxx@xxx.com" #定义邮件发件人
def addimg(src,imgid): #添加图片函数,参数1:图片路径,参数2:图片id
fp = open(src, 'rb') #打开文件
msgImage = MIMEImage(fp.read()) #创建MIMEImage对象,读取图片内容并作为参数
fp.close() #关闭文件
msgImage.add_header('Content-ID',imgid) #指定图片文件的Content-ID,
# <img> 标签src用到
return msgImage #返回msgImage对象
msg = MIMEMultipart('related') #创建MIMEMultipart对象,采用related定义内嵌资源#的邮件体
msgtext = MIMEText("""
#创建一个MIMEText对象,HTML元素包括表格<table>及图片
<img>
<table width="600" border="0" cellspacing="0" cellpadding="4">
<tr bgcolor="#CECFAD" height="20" duokan-code-cn>
<td colspan=2>*官网性能数据 <a href="monitor.domain.com">更多>></a></td>
</tr>
<tr bgcolor="#EFEBDE" height="100" duokan-code-cn>
<td><img src="cid:io"></td>
<td><img src="cid:key_hit"></td>
</tr>
<tr bgcolor="#EFEBDE" height="100"duokan-code-cn>
<td><img src="cid:men"></td>
<td><img src="cid:swap"></td>
</tr>
</table>
""","html","utf-8")
#<img>标签的src属性是通过Content-ID来引用的
msg.attach(msgtext) #MIMEMultipart对象附加MIMEText的内容
msg.attach(addimg("img/1.png","io")) #使用MIMEMultipart对象附加MIMEImage#的内容
msg.attach(addimg("img/2.png","key_hit"))
msg.attach(addimg("img/3.png","men"))
msg.attach(addimg("img/1.png","swap"))
msg['Subject'] = SUBJECT #邮件主题
msg['From']=FROM #邮件发件人,邮件头部可见
msg['To']=TO #邮件收件人,邮件头部可见
try:
server = smtplib.SMTP() #创建一个SMTP()对象
server.connect(HOST,"25") #通过connect方法连接smtp主机
server.starttls() #启动安全传输模式
server.login("xx@xxx.com", "xxxxx") # 邮箱账号登录校验
server.sendmail(FROM, TO, msg.as_string()) #邮件发送
server.quit() #断开smtp连接
print "邮件发送成功!"
except Exception, e:
print "失败:"+str(e)
相关文章