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

2024-05-15 22:50:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题在某种程度上类似于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有关?这件事让我头疼


Tags: to代码fromiotestimportmessageserver
1条回答
网友
1楼 · 发布于 2024-05-15 22:50:13

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

经过令人尴尬的长时间搜索;我找到了这个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功能中指定发件人和收件人

相关问题 更多 >