-1

I'm trying to send an OTP via email (which I save in a DB as well) and even though I believe my config is right because it logs in, it doesn't send messages (it did the first 2 times and then stopped):

 message = """Subject: Your OTP
    Hi, your your otp is {otp}"""
    from_address = "REDACTED"
    password = "REDACTED"
    context = ssl.create_default_context()
    print('xyz')
    msg = message.format(otp=otp)
    with smtplib.SMTP_SSL(host="smtppro.zoho.eu", port = 465, context=context) as server:
        print('xyz')
        server.login(from_address, password)
        print('logs')
        server.ehlo('127.0.0.1') ## i tried the ehlo() as well and without it all together
        print(email) ## prints this and then gets stuck
        server.sendmail(
            from_address,
            email,
            msg
        )
        print('sent')
        server.quit() ##i may had forgotten to have that the first 2 times
        print('quit')
    return "OTP sent to your email"

As you can see in the code block I had forgotten the quit() thing the first 2 times and I thought maybe there is something wrong with the session. I restarted the server 2 times in hopes to reset the connection.

Mind the comments I have made in the code block.

For the password I used my account password as well as an APP password (just for use in an app), and as I said there wasnt a problem with the log in.

After sometime (2-3 minutes) I get this in my terminal:

 File "/home/blank/.local/lib/python3.11/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blank/scripts/test/emails.py", line 56, in sendmail
    server.sendmail(
  File "/usr/lib/python3.11/smtplib.py", line 902, in sendmail
    (code, resp) = self.data(msg)
                   ^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/smtplib.py", line 580, in data
    (code, msg) = self.getreply()
                  ^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/smtplib.py", line 405, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Timus
  • 10,974
  • 5
  • 14
  • 28
  • Have you tried generating [Application Specific Password](https://www.zoho.com/mail/help/adminconsole/two-factor-authentication.html#alink7) if you have enabled TFA? – Shri Hari L Jun 20 '23 at 05:15
  • @ShriHariL Yes thats what i am using, App specific password.. i will try again but its very weird that i was able to send 3 emails. Having my own email server is something that will happen later, i just need to test for dev purposes for now – YasuoTouchedMySpaggett Jun 20 '23 at 10:40
  • You need an `f"""..."""` stringt for the variable to be interpolated, and an empty line between the headers and the body. But like everyone has been saying, use the `email` library to create a valid message for SMTP, especially if you are not an expert on the protocol and all its weird corner cases. – tripleee Aug 27 '23 at 19:38
  • Also, the argument to `ehlo` should be the sending system's identity, not some random string you found in Google. – tripleee Aug 27 '23 at 19:39
  • You don't need the `quit` if you use a `with` context manager. – tripleee Aug 27 '23 at 19:41

1 Answers1

0

3 things to try:

  1. Replace server.ehlo('127.0.0.1') by server.ehlo_or_helo_if_needed()
  2. Add server.ehlo_or_helo_if_needed() just after the with line (before the server.login line) (since its "if needed" you can add it at every function call of your SMTP object)
  3. Try to use the Python library email.message to generate an email.message.EmailMessage object you can pass to smtplib.SMTP_SSL (or to every SMTP object from smtplib) to the function server.send_message instead of manually make the string containing the raw message and passing it to server.sendmail. Also, try to avoid using Python 3.9 as I got same error on that version, and changing to Python 3.11 fixed the problem (combined with these 3 other tips).
HGStyle
  • 13
  • 5