I am sending email messages at different places in my application.
msg.send(fail_silently=True)
helps to avoid error page from displaying to end users when there is an error while sending the email. Is it possible to catch this error so that I make a log or execute a custom function?
Note: I am using Django 1.10.4 with Python 3.5.
As it says in the Django docs for send_email (https://docs.djangoproject.com/en/1.10/topics/email/#send-mail):
fail_silently: A boolean. If it’s False, send_mail will raise an smtplib.SMTPException. See the smtplib docs for a list of possible exceptions, all of which are subclasses of SMTPException.
So you can do:
from smtplib import SMTPException
try:
    msg.send()
except SMTPException as e:
    print('There was an error sending an email: ', e) 
                        Try This Once! It will cover any type of possible errors.
from smtplib import SMTPException
try:
    send_mail(subject, message, from_email, [to_email], fail_silently=False)
except BadHeaderError:              # If mail's Subject is not properly formatted.
    print('Invalid header found.')
except SMTPException as e:          # It will catch other errors related to SMTP.
    print('There was an error sending an email.'+ e)
except:                             # It will catch All other possible errors.
    print("Mail Sending Failed!")
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With