python怎么实现自动发邮件?这篇文章手把手教会你
陈立鑫
优草派
Python能实现很多我们人为非常繁琐的功能,这些繁琐的功能对于python来说也就是一段代码的事了,接下来小编给大家分享一个利用python自动发邮件,如果感兴趣的小伙伴可以耐心阅读下去,相信大家阅读完后一定能够有所收获。废话不多说,直接上代码。
一、普通文本邮件(作通知训练结束用 :smiley: )
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服务 mail_host = "smtp.163.com" # SMTP服务器 mail_user = "yourname" # 用户名 mail_pass = "xxx" # 密码(这里的密码不是登录邮箱密码,而是授权码) sender = 'yourname@163.com' # 发件人邮箱 receivers = 'othername@163.com'] # 接收人邮箱 content = 'Python Send Mail ! 训练结束!' title = 'Python SMTP Mail 训练结束' # 邮件主题 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) # 启用SSL发信, 端口一般是465 smtpObj.login(mail_user, mail_pass) # 登录验证 smtpObj.sendmail(sender, receivers, message.as_string()) # 发送 print("mail has been send to {0} successfully.".format(receivers)) except smtplib.SMTPException as e: print(e)
二、加强版附件传输邮件
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header # Files' Paths: file1 = 'mail.py' file2 = 'maill.py' # 收邮件的地址,可以多个。 Receivers = ['receiver1@163.com','receiver2@163.com'] # 邮件主题: title = 'Python SMTP 邮件(文件传输)' # 模拟服务器 # SMTP服务器 SMTPServer="smtp.163.com" # 发邮件的地址 Sender="yourname@163.com" # 发送者邮件的授权密码,去163邮箱设置里获取。并非是密码。 passwd="xxx" # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = Sender message['To'] = ",".join(Receivers) message['Subject'] = title # 邮件正文内容 message.attach(MIMEText('附件中是要传输的文件。 ', 'plain', 'utf-8')) message.attach(MIMEText('The files you need are as followed. ', 'plain', 'utf-8')) # 构造附件1 att1 = MIMEText(open(file1, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename={0}'.format(file1) message.attach(att1) # 构造附件2 att2 = MIMEText(open(file2, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename={0}'.format(file2) message.attach(att2) try: mailServer = smtplib.SMTP(SMTPServer, 25) # 25为端口号(邮件),0-1024都被系统占用了 # 登录邮箱 mailServer.login(Sender, passwd) # 需要的是,邮箱的地址和授权密码 # 发送文件 mailServer.sendmail(Sender, Receivers, message.as_string()) print("邮件发送成功") print("Mail with {0} & {1} has been send to {2} successfully.".format(file1,file2,Receivers)) except smtplib.SMTPException as e: print("Error: 无法发送邮件") print(e)
最后
我们可以把代码加到网络train.py的最后,但是千万不要忘了在train.py的开头加上以下代码:
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header
以上就是小编给大家带来的用python自动发邮件的方法了,希望大家通过阅读小编的文章之后能够有所收获!如果大家觉得小编的文章不错的话,可以多多分享给有需要的人,大家如果认可我们优草派网站的话也可以多多支持和关注,以便大家了解更多的知识点。
【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。