定时邮件发送或告警邮件实时发送是工作中常用的功能之一,该功能需要调用发送邮件模块,如下为亲测可用的Python编写的邮件发送代码,该代码使用qq邮箱可正常发送邮件,使用163邮箱时提示554错误码邮件无法正常发出。
实现邮件发送需要两个步骤,第一步为获取邮箱的用户名密码,在使用代码发送邮件时,该密码不是用户密码,而是授权码,如下演示了如何获取授权码以及邮件发送代码。
获取邮件授权码
在qq邮箱的”设置”界面中,打开“账户”的选项页,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务的模块,打开POP3和IMAP服务,见如下,并获取授权码,该授权码需要在Python代码中使用。
邮件发送代码示例
如下为邮件发送代码,请把星号替换为你所使用的真实的邮箱。
import smtplib
from email.header import Header
from email.mime.text import MIMEText
def send_email_test():
mail_host = "smtp.qq.com"
mail_user = "*******@qq.com"
mail_pass = "***************" # 授权密码,非登录密码
sender = '*******@qq.com'
receivers = ['*******@qq.com']
content = 'Python example'
title = 'this is a super mail!'
send_email(mail_host, mail_user, mail_pass, sender, receivers, title, content)
def send_email(mail_host, mail_user, mail_pass, sender, receivers, title, content):
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = title
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("mail has been send successfully.")
except smtplib.SMTPException as e:
print(e)
if __name__ == '__main__':
send_email_test()
# receiver = '***'
# send_email2(mail_host, mail_user, mail_pass, receiver, title, content)
在运行后打印如下,查看邮箱,可以收到相应邮件
如果您喜欢这边文章,请记得点赞和评论哦!
2018年11月3日 香港演员蓝洁瑛去世,享年55岁,
漂亮的她,一生不幸,
历经雪藏、情变、受辱、破产、自杀,
晚年平淡凄凉,
愿天堂里不再有磨难!