英文:
Python doesn't send email using smtpd, I get no errors but no emails are delivered
问题
我尝试使用Python发送电子邮件,但我没有收到任何邮件。我已经检查了垃圾邮件文件夹,但仍然没有结果。
我的代码:
import smtplib
connection = smtplib.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs=email, msg="Hello")
connection.close()
我没有收到任何错误,但没有邮件被送达。
英文:
I tried to send an email via Python, but I don't get any mail. I have checked the spam folder but still no results.
My code:
import smtpd
connection = smtpd.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs=email, msg="Hello")
connection.close()
I get no errors, but no mail is delivered.
答案1
得分: 1
smtpd
模块从版本3.6开始被弃用。因此,我将改用smtplib
。
import smtplib, ssl
# 创建安全的SSL上下文
cont = ssl.create_default_context()
server = smtplib.SMTP(smtp_server, port=587)
server.starttls(context=cont)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
server.quit()
为了使代码更清晰,应在使用特定代码行之前定义sender_email
,receiver_email
和message
。
英文:
The smtpd
module is deprecated since version 3.6. Thus, I will instead use smtplib
.
import smtplib, ssl
# Create secure SSL context
cont = ssl.create_default_context()
server = smtplib.SMTP(smtp_server, port = 587)
server.starttls(context = cont)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
server.quit()
For a cleaner code, sender_email
, receiver_email
and message
should be defined before using the particular line of code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论