使用 smtplib 向 mailtrap 发送电子邮件仅在代码不在函数或类中时才有效



这个问题有点类似于python:发送邮件,在"with"块内失败。

我正在使用Python(3.6(向mailtrap smtp发送电子邮件。Mailtrap实际上为您提供了smtplib的集成代码,如下所示:

import smtplib
sender = "Private Person <from@smtp.mailtrap.io>"
receiver = "A Test User <to@smtp.mailtrap.io>"
message = f"""
Subject: Hi Mailtrap
To: {receiver}
From: {sender}
This is a test e-mail message."""
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD>")
server.sendmail(sender, receiver, message)

如果我将上面的代码放在模块中并运行它,则上面的代码工作得很好。我转到邮件陷阱收件箱并验证电子邮件是否在那里。但是我想将其封装在这样的函数中:


import smtplib
from socket import gaierror

def test():
sender = "Test Dev <from@smtp.mailtrap.io>"
receiver = "Test User <to@smtp.mailtrap.io>"
message = f"""
Subject: Hi there
To: {receiver}
From: {sender}
TESTING"""
try:
with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login("<MYUSER>", "<MYPASSWORD")
print("Sending email")
server.sendmail(sender, receiver, message)
print('Sent')

except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
if __name__ == "__main__":
test()

这行不通。为什么?这是输出: 输出图像 没有连接错误或任何其他异常。但是我去邮件陷阱,在那里找不到电子邮件。

这是邮件陷阱问题还是与 smtplib 有关?我正在为这个而努力

我遇到了同样的问题,无法解决它。我确实注意到,当我将消息设置为空字符串时,它起作用了。

经过令人尴尬的长时间搜索;我找到了这篇文章,它为我指明了解决方案。

您必须设置电子邮件的 MIME 类型。因此,不仅仅是传递字符串,而是传递消息对象:

message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver

。然后最终

server.sendmail(sender, receiver, message.as_string())

我的完整发送电子邮件功能如下所示:

def send_mail(self):
message = MIMEText("TEST!")
message["Subject"] = "Alert!"
message["From"] = sender
message["To"] = receiver
try:
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.set_debuglevel(1)
server.ehlo()  # Can be omitted
server.starttls(context=context)
server.ehlo()  # Can be omitted
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
except Exception as e:
print('everything else')

不幸的是,您必须在消息对象和发送电子邮件功能中指定发送方和接收方。

相关内容

  • 没有找到相关文章

最新更新