How to get the SMTP server response code in Django?

1k Views Asked by At

Goal:

Hi! How can I get the SMTP response codes through Django, similar to return values given from the smtplib module??? I want to use Django's api instead of having to use that, and I see nothing in Django's email docs.

I know send_mail(), send_mass_mail() , and EmailMessage.send_messages(...) all have return values that show the number of successfully delivered messages... But I want the response codes for all of them. The point is to get proof that an email is sent, bad email address, etc, like smtp response codes show.

And it's looking to me like I'd have to make a custom email backend for this, and subclass from BaseEmailBackend... It's using smtplib anyway.

Example code for smtplib's response code

import smtplib
obj = smtplib.SMTP('smtp.gmail.com', 587)
response = obj.ehlo()
print(response)

# Obviously this doesn't send a message yet, but I want response[0]
(250, b'smtp.gmail.com at your service, [111.222.33.44]\nSIZE 31234577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')
1

There are 1 best solutions below

0
iklinac On

If you just want to check if mail is sent you can use return value of send_mail() function

The return value will be the number of successfully delivered messages (which can be 0 or 1 since it can only send one message).

Django does catch smtplib errors and returns 0 if any error occurred or returns exception if fail_silently is false ( default true)

from django.core.mail.backends.smtp.EmailBackend source _send():

try:
    self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
except smtplib.SMTPException:
    if not self.fail_silently:
            if not self.fail_silently:
            raise
        return False
    return True

same thing on open()