如供第三方使用,可在邮箱设置中,申请获取授权码,然后用授权码替换邮件中邮箱密码password。
import re
from email.mime.text import MIMEText
from email.header import Header
import smtplib
MailAddress = {
"username": "***@163.com",
"password": "ojamrqshpltzbahe"
}
class Email(object):
def __init__(self, to_addr, message):
super().__init__()
self.from_addr = MailAddress["username"]
self.password = MailAddress["password"]
self.to_addr = to_addr
self.message = message
def send(self):
msg = MIMEText(self.message, 'plain', 'utf-8')
msg['Subject'] = Header('程序监控信息', 'utf-8')
msg['From'] = 'Zhang<%s>' % self.from_addr
msg['To'] = self.to_addr
if re.search("163.com", self.from_addr):
smtp_server = 'smtp.163.com'
elif re.search("qq.com", self.from_addr):
smtp_server = 'smtp.qq.com'
try:
server = smtplib.SMTP_SSL(smtp_server, 465) # 这里使用ssl,端口为465 / 994
# print('开始登录')
server.login(self.from_addr, self.password) # 登录邮箱
# print('登录成功')
server.sendmail(self.from_addr, self.to_addr, msg.as_string()) # 将msg转化成string发出
server.quit()
# print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败", e)
# 调用方法:
Email('***@163.com', 'ok_message').send()