Pyhton发送邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pyhton发送邮件相关的知识,希望对你有一定的参考价值。
Python使用smtplib和email库发送邮件,发送html格式正文,插入图片,以及发送execl等文件。实例代码如下:
#/usr/bin/env python
#-*- coding:utf-8 -*-
#auther:yuanmuc
#email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.mime.application import MIMEApplication
import time
#收件人列表
mailto_list = [‘[email protected]‘,‘[email protected]‘]
#发件人用户名
mail_user = "monitor"
#邮件域后缀
mail_postfix = "localtest"
def Send_Mail(to_list,sendinfo):
#邮件标题
title = "网络质量告警" + time.strftime(‘%Y%m%d‘,time.localtime(time.time()))
#增加图片附件
def addimg(src,imgid):
fd = open(src,‘rb‘)
msgImage = MIMEImage(fd.read())
fd.close()
msgImage.add_header("Content-ID",imgid)
return msgImage
#发送execl附件
def attachexecl(f):
part = MIMEApplication(open(f,‘rb‘).read())
part.add_header("Content-Disposition",‘attachment‘,filename=f)
msg.attach(part)
msg = MIMEMultipart(‘related‘)
#html邮件正文
msgtext = MIMEText(sendinfo,"html","utf-8")
msg.attach(msgtext)
#添加图片,imgid是html中的图片id
imgfile = "a.png"
imgid = "hello"
msg.attach(addimg(imgfile,imgid))
#添加execl附件
execlfile = "test.xlsx"
attachexecl(execlfile)
#连接邮件服务器
me = mail_user + "@" + mail_postfix
msg["Subject"] = title
msg["From"] = me
msg["To"] = ";".join(to_list)
send_to = to_list
try:
server = smtplib.SMTP("192.168.1.192")
server.set_debuglevel(1)
server.sendmail(me,send_to,msg.as_string())
return True
except Exception e:
print str(e)
def Main(sendinfo):
if Send_Mail(mailto_list,sendinfo):
print "发送成功"
else:
print "发送失败"
if __name__ == ‘__main__‘:
sendhtml = "<h1>这是一个测试</h1><img src="cid:hello" width=‘650‘ height=‘220‘/>"
Main(sendhtml)
以上是关于Pyhton发送邮件的主要内容,如果未能解决你的问题,请参考以下文章
Javascript - 使用 HTML 片段通过电子邮件发送 JSON 输出
pyhton—opencv直线检测(HoughLines)找到最长的一条线