使用 python 我想从我的应用程序发送电子邮件,但它显示错误
SMTP AUTH extension not supported by server
程序代码,
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Test Mail"
body = "Test mail from python"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.example.com', 25)
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
Telnet 输出:
ehlo test1.example.com
250-hidden
250-HELP
250-SIZE 104857600
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-STARTTLS
250 OK
我需要从应用程序进行身份验证并发送邮件。
登录和发送邮件之前需要连接。
server = smtplib.SMTP('smtp.example.com', 25)
server.connect("smtp.example.com",465)
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
无需调用
smtp.connect()
和smtp.ehlo()
,因为它们是由SMTP()
和smtp.starttls()
自动调用的。只需将端口设置为 587
而不是 28
即可解决该问题。
对于客户端使用,如果您对安全策略没有任何特殊要求,强烈建议您使用
create_default_context()
函数来创建 SSL 上下文。它将加载系统的可信 CA 证书,启用证书验证和主机名检查,并尝试选择合理安全的协议和密码设置。
一般来说,您需要使用
email
包的功能来构建电子邮件消息,然后可以通过 send_message()
发送。
import smtplib, ssl
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content("The body of the email is here")
msg["Subject"] = "An Email Alert"
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
context=ssl.create_default_context()
with smtplib.SMTP("smtp.example.com", port=587) as smtp:
smtp.starttls(context=context)
smtp.login(msg["From"], "p@55w0rd")
smtp.send_message(msg)
这可能只是我正在使用的服务器,但即使在实现了可接受的解决方案之后,也遇到了与OP相同的错误。原来服务器不需要登录,所以删除行
server.login(fromaddr, "password")
后,错误消失了并且它起作用了。
第一次点击是启用您的 Gmail 帐户通过其他应用程序发送电子邮件,在此部分中允许:
https://myaccount.google.com/lesssecureapps
然后,您应该可以发送电子邮件
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
msg = MIMEMultipart()
message = "This is an email"
password = "yourpasswordemailsender"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "Title of email"
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
您需要在登录前“starttls”。
import smtplib
s = smtplib.SMTP('smtplib.gmail.com',587)
s.ehlo()
s.starttls()
s.login('frmaddr','password')
try:
s.sendmail('fromaddr','toaddr','message')
except:
print (failed)
EMAIL_USE_TLS=True
应该足够了。