gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:18:20 25 4
gpt4 key购买 nike

这个问题有点类似于 python: sending a mail, fails when inside a "with" block .

我正在使用 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)

如果我将上面的代码放在一个模块中并运行它,上面的代码就可以正常工作。我去 mailtrap 收件箱并验证电子邮件是否在那里。但是我想将它封装在这样的函数中:

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()

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

这是一个邮件陷阱问题还是与 smtplib 有关?我在这个问题上绞尽脑汁

最佳答案

我遇到了同样的问题,无法解决这个问题。我确实注意到,当我将消息设为空字符串时,它起作用了。
经过令人尴尬的长时间搜索;我找到了 post这为我指出了解决方案。
您必须设置电子邮件的 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')
不幸的是,您必须在 message 对象和 sendemail 函数中指定发送者和接收者。

关于python - 仅当代码不在函数或类中时,使用 smtplib 向 mailtrap 发送电子邮件才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60043733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com