Python doesn't send email using smtpd, I get no errors but no emails are delivered

huangapple go评论71阅读模式
英文:

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_emailreceiver_emailmessage

英文:

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.

huangapple
  • 本文由 发表于 2023年3月9日 17:59:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定