Exceptions - SMTPException














































Exceptions - SMTPException



In this article we will discuss about exceptions in smtplib. We will explain almost every exception that we may face, with examples. Also check out my previous articles on SMTP module for better understanding, it may help you out.

EXCEPTIONS

SMTP module has a wide list of exceptions. Here , I have tried to list all of those , define them and explain them with the help of an example. I will describe each of them in a separate article.
Those exceptions are -

( i ) exception smtplib.SMTPException
( ii) exception smtplib.SMTPServerDisconnected
(iii) exception smtplib.SMTPResponseException
(iv) exception smtplib.SMTPSenderRefused
( v) exception smtplib.SMTPRecipientsRefused
(vi) exception smtplib.SMTPDataError
(vii) exception smtplib.SMTPConnectError
(viii) exception smtplib.SMTPHeloError
(ix) exception smtplib.SMTPNotSupportedError
(x)  exception smtplib.SMTPAuthenticationError


Now we will discuss each exceptions in detail-

(i) exception smtplib.SMTPException

This exception is a Subclass of OSError that is the base exception class for all the other exceptions provided by this module.
This exception is raised when a system function returns a system-related error, including I/O failures such as"file not found" or "disk full" (not for illegal argument types or other incidental errors).
The following code is example for showing how to use smtplib.SMTPException. This code is from open source Python projects.

def send_mail(server, from_address, from_name, to_address, subject, body_arg, return_addr, tls):

msg = MIMEMultipart('alternative')
msg['To'] = to_address
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.add_header('reply-to', return_addr)
msg.add_header('from', from_name + "<" + from_address + ">")

part1 = MIMEText(body_arg, 'plain')
part2 = MIMEText(body_arg, 'html')

msg.attach(part1)
msg.attach(part2)

try:
smtp = smtplib.SMTP(server)
smtp.set_debuglevel(VERBOSE)
smtp.sendmail(from_address, to_address, msg.as_string())
smtp.quit()
except smtplib.SMTPException:
print FAIL + "[-] Error: unable to send email to ", to_address, ENDC

Here, In this example we are sending a mail to the client and we are already prepared for handling this exception if it may occur. If the system catches this exception then it will exit with an error  message stating error type and unable to send mail.


Note:- In the next articles we will discuss on SMTPServerDisconnected exception . Keep on checking.

Comments