使用函数进行邮件发送的示例

看了武 sir的 Python基础之函数篇

里面有一个利用函数来实现自动分发送服务器告警的示例,也进行了一次 run,没想到居然真的成功了 ...

#!/usr/bin/env python
# -*- coding:utf8 -*-

def sendmail():
    try:
        import smtplib
        from email.mime.text import MIMEText
        from email.utils import formataddr

        msg = MIMEText('您的服务器现在负荷过大,需要关注CPU和内存占用情况!', 'plain', 'utf-8') #邮件内容
        msg['From'] = formataddr(["监控台", '[email protected]'])
        msg['To'] = formataddr(["Even", '[email protected]'])
        msg['Subject'] = "您的服务器现在负荷过大,需要关注CPU和内存占用情况!"  #邮件主题

        server = smtplib.SMTP("smtp.163.com", 25)
        server.login("[email protected]", "******")     #监控台的邮箱和******SMTP授权码
        server.sendmail('[email protected]', ['[email protected]', ], msg.as_string())
        server.quit()
    except:
        return False
    else:
        return True

ret = sendmail()
if ret == True:
    print("发送成功")
else:
    print("发送失败")
def sendmail():

需要注意的是要开启监控台发送者邮箱的对应 SMTP服务,并设置相应的授权码

猜你喜欢

转载自www.cnblogs.com/evenyao/p/9170493.html
今日推荐