我经常需要用手机看服务器的运行情况,所以就写一个脚本,通过邮件把服务器运行情况发送给我,直接手机可以查看炼丹状态。事实证明还是很有用的,所以撰写一篇博文将脚本分享给大家。这里用到smtplib
和email
两个python包。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipartclass Mailer:def __init__(self, account, password):self.sender = smtplib.SMTP_SSL('smtp.qq.com')self.login(account, password)self.account = accountself.msg = Nonedef login(self, account, password):if "qq.com" not in account:print("Only QQ mail be supported!")raise Errorself.sender.login(account, password)def write_mail(self, header, content):self.msg = MIMEMultipart()self.msg["Subject"] = Header(header, "utf-8")self.msg["From"] = self.accountself.msg.attach(MIMEText(content, "plain", "utf-8"))def send_to(self, receiver):self.msg["To"] = receiverself.sender.sendmail(self.account, receiver, self.msg.as_string())print(self.msg.as_string())def _main():# login your QQ mailmailer = Mailer('xxxxxx@qq.com','your password')# write mailmailer.write_mail("标题", "测试内容。")# send mail to any mailmailer.send_to("xxxxxxx@163.com")if __name__ =='__main__':_main()
脚本由本人原创,借用请说明出处。这里只能使用QQ邮箱,如果使用其他邮箱需要改写对应的smtp服务器。同时,使用发送方邮箱时需要在设置中开启SMTP服务,否则将会无法登录。
如何开启SMTP服务器?
- 用网页登录对应邮箱;
- 找到设置;
- 在设置中找到“开启POP3/IMAP/SMTP/Exchange/CardDAV服务”;
- 授权开启即可。
有疑问可留言交流~