编程过程中经常会遇到有要发送邮件的情况,本文主要是介绍了一下在Python里实现发送邮件的方法,当然是借助了第三方的smtp服务器来实现的,这里我采用的是腾讯的smtp服务器,发送邮件的关键代码为:
import smtplib from email.mime.text import MIMEText from email.header import Header smtp_server = "smtp.qq.com" smtp_port = 465 smtp_username = "[email protected]" smtp_password = "这里写授权码" def sendmail(sender, receivers, Subject, Content, sendername): mail = MIMEText(Content, "plain", "utf-8") mail["From"] = Header(sendername, "utf-8") mail["Subject"] = Subject try: server = smtplib.SMTP_SSL(smtp_server, smtp_port) server.login(smtp_username, smtp_password) server.sendmail(sender, receivers, mail.as_string()) server.quit() except smtplib.SMTPException as E: print("发送邮件失败!异常信息:", E) if __name__ == "__main__": sendmail("[email protected]", ["[email protected]", "[email protected]"], "吾八哥邀您一起来学Python", "吾八哥学Python,发送邮件测试...", "吾八哥")
运行上述代码后,我邮箱里已经收到邮件了,如下图:
支持定义发送者的名称,发送者邮箱,主题以及内容。如果要投入实际生成环境,并且发送的频率比较大的话还是需要做一定的改造的,例如定义邮件信息结构,做列队处理等等,这个后续再做研究了!
发表评论