前言:
找回密码时,需要后台给用户发送验证信息,本篇实现一个基于python的自动发邮件程序。
需要使用的库 :smtplib
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
代码如下:
#coding:utf-8
import smtplib
#from email.mime.text import MIMEText
from email.MIMEText import MIMEText
from email.utils import formataddr
def mail(my_user,repwd):
ret=True
my_sender='xxx@163.com' #发件人邮箱,需开启smtp服务
pwd='密码' #如是网易,此为客户端授权码
try:
str_text='重置的密码: '+repwd #邮件内容
msg=MIMEText(str_text,'plain','utf-8')
msg['From']=my_sender
msg['To']=my_user
msg['Subject']="官方通知" #邮件主题
server=smtplib.SMTP("smtp.163.com",25)
server.login(my_sender,pwd)
server.sendmail(my_sender,my_user,msg.as_string())
server.quit()
except Exception:
ret=False
return ret
my_user='yyy@qq.com' #收件人邮箱
repwd='aaaaa' #重置的密码
ret=mail(my_user,repwd)
if ret:
print("Success")
else:
print("Filed")
注意事项:
1、
smtplib.SMTPAuthenticationError: (535, ‘Authentication failed’)
需要‘发送邮箱’开启smtp协议,去邮箱设置,建议使用163测试,设置完成后还要获取 客户端授权码
,程序是客户端登陆,要用此密码,稍微麻烦点,但对比qq邮箱开启smtp服务分分钟让我想注销账户的体验,163还是省事很多。
2、
No module named
这种错误查一查,python版本不一样,叫法会有区别,可以启动解释器,import 模块后 dir(模块)检查
3、Python已经封装了email模块,注意自己程序的名字不要叫 email.py
!