Alert

Posted by JD on June 7, 2018

脚本出现Error需要第一时间发出警告。记录下我所使用的方法。

Email

邮件方式方便简单,可以使用python中的smtplibemail

smtplib主要是负责发送邮件,常使用connectloginsendemail,分别是连接邮件服务器、登录账号和发送邮件。

email主要是负责构建邮件,常使用email.headeremail.mime.text.MINEText,前者是构造头部信息(From、To和Subject),后者构造文件内容。

python发送简单邮件

import configparser
import smtplib
from email.mime.text import MIMEText
from email.header import Header

#发送邮件,传入邮件主题,邮件内容
def send_email(subject,mimetext):
    try:
        #读取email配置文件信息
        cf = configparser.ConfigParser()
        cf.read("email.properties")
        mail_host = cf.get("email", "mail_host")
        mail_port = cf.get("email", "mail_port")
        mail_user = cf.get("email", "mail_user")
        mail_pass = cf.get("email", "mail_pass")
        sender = cf.get("email", "sender")
        receivers = cf.get("email", "receivers").split(',')
        message = MIMEText(mimetext, 'plain', 'utf-8')

        str_receivers = ''
        for index in range(len(receivers)):
            str_receivers = str_receivers + '<' + receivers[index] + '>,'
        str_receivers = str_receivers[:-1]

        message['From'] = Header(sender, 'utf-8')
        message['To'] = Header(str_receivers, 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        server = smtplib.SMTP()
        server.connect(mail_host, mail_port)
        server.login(mail_user, mail_pass)
        server.sendmail(sender, receivers, message.as_string())
        server.close()
    except smtplib.SMTPException as ex:
        raise Exception(ex)

注意:发送QQ邮件需建立SSL安全连接,将smtplib.SMTP()改成smtplib.SMTP_SSL()

邮箱 POP3服务器(端口995) SMTP服务器(端口465或587)
qq.com pop.qq.com smtp.qq.com
163.com pop.163.com smtp.163.com
import configparser
import smtplib
from email.mime.text import MIMEText
from email.header import Header

#发送邮件,传入邮件主题,邮件内容
def send_email(subject,mimetext):
    try:
        #读取email配置文件信息
        cf = configparser.ConfigParser()
        cf.read("email.properties")
        mail_host = cf.get("email", "mail_host")
        mail_port = cf.get("email", "mail_port")
        mail_user = cf.get("email", "mail_user")
        mail_pass = cf.get("email", "mail_pass")
        sender = cf.get("email", "sender")
        receivers = cf.get("email", "receivers").split(',')
        message = MIMEText(mimetext, 'plain', 'utf-8')

        str_receivers = ''
        for index in range(len(receivers)):
            str_receivers = str_receivers + '<' + receivers[index] + '>,'
        str_receivers = str_receivers[:-1]

        message['From'] = Header(sender, 'utf-8')
        message['To'] = Header(str_receivers, 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        server = smtplib.SMTP_SSL(mail_host, mail_port)
        server.login(mail_user, mail_pass)
        server.sendmail(sender, receivers, message.as_string())
        server.close()
    except smtplib.SMTPException as ex:
        raise Exception(ex)

若想发送HTML格式邮件,需将MIMEText(mimetext, 'plain', 'utf-8')中的plain改成html

也可在HTML格式邮件加入图片,如下

import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
import configparser

cf = configparser.ConfigParser()
cf.read("email.properties")
mail_host = cf.get("email", "mail_host")
mail_port = cf.get("email", "mail_port")
mail_user = cf.get("email", "mail_user")
mail_pass = cf.get("email", "mail_pass")
sender = cf.get("email", "sender")
receivers = cf.get("email", "receivers").split(',')

message = MIMEMultipart()

str_receivers = ''
for index in range(len(receivers)):
    str_receivers = str_receivers + '<' + receivers[index] + '>,'
str_receivers = str_receivers[:-1]

message['From'] = Header(sender, 'utf-8')
message['To'] = Header(str_receivers, 'utf-8')
message['Subject'] = Header('test', 'utf-8')

mail_msg = """
<p>Python 邮件发送测试...</p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
message.attach(MIMEText(mail_msg, 'html', 'utf-8'))

with open(r'C:\Users\JD\Desktop\timg.jpg', 'rb') as f:
    mime = MIMEBase('image', 'png', filename='timg.png')
    mime.add_header('Content-ID', '<image1>')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    message.attach(mime)

server = smtplib.SMTP_SSL(mail_host, mail_port)
server.login(mail_user, mail_pass)
server.sendmail(sender, receivers, message.as_string())
server.close()

发送附件,只需修改部分

import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
import configparser

cf = configparser.ConfigParser()
cf.read("email.properties")
mail_host = cf.get("email", "mail_host")
mail_port = cf.get("email", "mail_port")
mail_user = cf.get("email", "mail_user")
mail_pass = cf.get("email", "mail_pass")
sender = cf.get("email", "sender")
receivers = cf.get("email", "receivers").split(',')

message = MIMEMultipart()

str_receivers = ''
for index in range(len(receivers)):
    str_receivers = str_receivers + '<' + receivers[index] + '>,'
str_receivers = str_receivers[:-1]

message['From'] = Header(sender, 'utf-8')
message['To'] = Header(str_receivers, 'utf-8')
message['Subject'] = Header('test', 'utf-8')

message.attach(MIMEText('send with file...', 'plain', 'utf-8'))

with open(r'C:\Users\JD\Desktop\timg.jpg', 'rb') as f:
    mime = MIMEBase('image', 'png', filename='timg.png')
    mime.add_header('Content-Disposition', 'attachment', filename='timg.png')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    message.attach(mime)

server = smtplib.SMTP_SSL(mail_host, mail_port)
server.login(mail_user, mail_pass)
server.sendmail(sender, receivers, message.as_string())
server.close()

Short Messaging Service

python发送短信的方式很多,我这边使用twilio

需要先在官网注册一个账号,目前国内已经注册不了,需要翻墙。

进入官网,点击sign up,然后进入下面的界面

进行一系列无脑验证后,就创建好账号,进入账号可以看到自己的信息,最主要的就是ACCOUNT SIDAUTH TOKEN

其中我们可以得到一个twilio phone number,也就是client.messages.createfrom_

在twilio中,免费账号只可以发给认证过的手机号,下面是认证界面

这样就完成了我们全部的准备工作。下面是发短信的代码。

from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# Your Auth Token from twilio.com/console
auth_token  = "your_auth_token"

client = Client(account_sid, auth_token)

message = client.messages.create(
    to="+15558675309", 
    from_="+15017250604",
    body="Hello from Python!")

print(message.sid)

运行后,手机就可以收到短信了,啦啦啦~

申请的免费账号,前缀无法去掉。