Python 发邮件,全文邮件服务器以 smtp.qq.com 为前提:
如下错误:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
方法一:使用相关模块,这里拿QQ为例,这里端口号是:465
#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
_user = "发送者@qq.com"
_pwd = "独立密码非qq密码"
_to = "接受者@qq.com"
msg = MIMEText("www.baidu.com")
msg["Subject"] = "Python 发送邮件测试"
msg["From"] = _user
msg["To"] = _to
i = 0
while i < 1:
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(_user, _pwd)
s.sendmail(_user, _to, msg.as_string())
s.quit()
print("Success!")
except smtplib.SMTPException as e:
print ("Falied,%s" %e)
i = i + 1
方法二:Django 框架发送邮件,settings.py 中配置如下:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# smpt服务地址
EMAIL_HOST = 'smtp.qq.com'
#端口号
EMAIL_PORT = 25
#发送邮件的邮箱
EMAIL_HOST_USER = '发送者@qq.com'
#在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = '客户端授权密码'
#收件人看到的发件人
EMAIL_FROM = 'python<发送者@qq.com>'
views.py中这样使用:
from django.core.mail import send_mail
send_mail('测试成功', '这是邮件正文', settings.EMAIL_FROM, ['接受者@qq.com'])
很简单,关键不在写代码,在一些坑里,第一种方式端口号是465,走框架的方式,尽然端口号需要是 25 ,至于为什么接下来查,这里浪费了点时间,如果使用465端口一直失败,不妨试试25,下面是一个同学同样踩过的坑: