这个问题在某种程度上类似于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 没有连接错误或任何其他异常。然而,我去了mailtrap,却没有在那里找到邮件
这是邮件陷阱问题还是与smtplib有关?这件事让我头疼
我也遇到了同样的问题,我无法理解。我确实注意到,当我将我的消息设置为空字符串时,它就起作用了
经过令人尴尬的长时间搜索;我找到了这个post,它为我指明了解决方案
您必须设置电子邮件的MIME类型。因此,不只是传递字符串,而是传递消息对象:
。。。然后最终
我的完整发送电子邮件功能如下所示:
不幸的是,您必须在message对象和sendemail功能中指定发件人和收件人
相关问题 更多 >
编程相关推荐