`
897371388
  • 浏览: 530534 次
文章分类
社区版块
存档分类
最新评论

python发邮件通知

 
阅读更多

有时候工作中需要一观察一些数据,当达到一直的阈值会告警,而告警常用的是通过邮件来做,下面的这段是和大家分享如何使用python做邮件告警。

首先,找到使用的邮件服务器的地址,及一个合法的用户,一般公司有自己的邮件服务器,为了方便,我使用163邮箱来举例子。

执行ping smtp.163.com命令,查看邮件的地址。


那么邮件服务器的地址为123.125.50.135

第二,把需要的附件准备好,可以使用python写文件的方式。

第三,正式发邮件:

#!/usr/bin/env python2.6
# -*- coding: UTF-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText

from email.utils import COMMASPACE,formatdate
from email import encoders

import os

#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]):


msg = MIMEMultipart()
msg['From'] = fro
msg['Subject'] = subject
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text))

for file in files:
part = MIMEBase('application', 'octet-stream')
part.set_payload( open(file,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part)

import smtplib
smtp = smtplib.SMTP(server['name'])
smtp.login(server['user'], server['passwd'])
smtp.sendmail(fro, to, msg.as_string())
smtp.close()

if __name__ == "__main__":
server={}
server['name'] = 'smtp.163.com'# 如果是写自己公司的邮件服务器,请使用IP的方式,不然会有DNS解析的问题
#server['name'] = '123.125.50.135:25'
server['user'] = 'Yourname@163.com' # 用户名
server['passwd'] = 'yourPWD' # 密码
fro = 'ssergsw@163.com'
to = ['xxx@163.com']
subject = "test email "
text = "this is a test mail, hello"
files = ["info.txt"]
send_mail(server, fro, to, subject, text, files)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics