Reputation: 753
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.
Upvotes: 4
Views: 9650
Reputation: 3223
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)
Upvotes: 14
Reputation: 2646
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!")
Upvotes: 1