使用 smtplib 向 mailtrap 发送电子邮件仅在代码不在函数内或 class 时有效
Using smtplib to send an email to mailtrap only works when code is not within function or class
这个问题有点类似于。
我正在使用 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)
如果我将上面的代码放在一个模块中并且 运行 it.I 转到 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 = 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')
很遗憾,您必须在邮件对象和发送邮件函数中指定发件人和收件人。
这个问题有点类似于
我正在使用 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)
如果我将上面的代码放在一个模块中并且 运行 it.I 转到 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 = 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')
很遗憾,您必须在邮件对象和发送邮件函数中指定发件人和收件人。