Search code examples
pythonemailemail-validationsmtplib

In Python's smtplib package, is there a way to create a notification if sent emails bounce?


Currently, I am using Python's smtplib package to send emails. I have a large list of emails I would like to verify if they exist. In most cases, getting a 250 message would suffice. However, for aol.com, you can put any handle and they will still say it exists.

Therefore, I am sending a message one by one. Is there a way to program a routine where if an email doesn't go through, smtplib would notify me of the non-working email? thanks!


Solution

  • If the email cannot be sent, it will raise an exception as per the docs. You could do something like the following:

    cantSendErrors = (smptlib.SMTPHeloError, smptlib.SMTPSenderRefused)  # Put any other suitable exceptions in this tuple
    try:
        smptlib.sendmail(args, go, here)
    except cantSendErrors:
        # Your code here. You could email yourself or write the error to log file for later review, your choice.