因为现在邮箱都支持smtp服务,需要你手动打开,并且获得授权码。以qq邮箱为例,
这里会要求你发送短信,验证,通过后会提供给你一个授权码,记下这个授权码,写入程序内
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
my_sender = '[email protected]'#发件人
my_pass = 'xxxx'#授权码
my_user = '[email protected]'#收件人
my_context = '测试监控进程操作'
my_title = '来自服务器的信息'
my_chengname = '服务器监控监控'
def mail():
ret = True
try:
msg = MIMEText(my_context, 'plain', 'utf-8')
msg['From'] = formataddr([my_chengname, my_sender])
msg['To'] = formataddr(["收件人昵称", my_user])
msg['Subject'] = my_title
server = smtplib.SMTP_SSL("smtp.qq.com", 465)#qq邮箱的服务器和端口
server.login(my_sender, my_pass)
server.sendmail(my_sender, [my_user, ], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
ret = mail()
if ret:
print("Mail send is ok ...")
else:
print("Mail send is error ...")
邮件会自动归进垃圾邮箱,记得翻开一下,设置为信任,就可以了