Quantcast
Channel: Active questions tagged email - Stack Overflow
Viewing all articles
Browse latest Browse all 30082

Using smtplib to send an email to mailtrap only works when code is not within function or class

$
0
0

this question is somehow similar to python: sending a mail, fails when inside a "with" block .

I'm using Python (3.6) to send emails to mailtrap smtp. Mailtrap actually provides you with the integration code for smtplib which is the one below:

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)

The code above works just fine if I place it in a module and run it.I go to mailtrap inbox and verify that the email is there. However I want to encapsulate this in a function like this:


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

This doesn't work. WHY? Here is the output: output image There's no connection error or any other exception. However I go to mailtrap and don't find the email there.

Is this a mailtrap issue or is it related to smtplib ? I'm cracking my head around this one


Viewing all articles
Browse latest Browse all 30082

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>