Python exception to email

Email Exception Handling in Python

In this article, we show how to handle email exception errors in Python.

When sending emails in Python, there are a number of things that you must do, including connecting to the email host such gmail.

You then need to log in to an actual email account such as «» with a password of «abc123»

There are just a number of things that can go wrong during the sending email process.

You may not be able to connect to the email hosting provider.

There may be an incorrect username-password combination.

In other words, there are a number of errors that can occur in the process.

If you’re running this in a production environment, you don’t want the machine-generated error to be shown, such as a 535 error, which a user may not understand. You want to put a customized message such as, «The username and password combination does not match»

So, we’ll show how to handle email exception errors in a program in Python.

So, before, we do that, let’s go over a simple Python script that sends an email message.

The code below sends a simple email message, «Hey»

So, this is the generic way, we can send an email, «Hey»

Now, we’ll create the code so that email exceptions are handled.

Generic Email Exception Handling

So, the first thing we’ll go over is how to handle all exceptions generically instead of each specific error.

What is meant by this is that if any error occurs at all, whether it’s a problem connecting to the email service provider, incorrect username/password combination, or any other error, we will handle them all the same. So it’s generic.

So, to handle all email errors generically, we can use the following code below.

So, let’s go over what we’ve done in this code.

Now, because we’re going to handle exceptions, we import SMTPException.

What this class, SMTPException, does is it is called if an exception error occurs anywhere in our code.

We use try-except statements to try a block of code. If this block of code does not work, what exists after except will be executed, which is our error message, «An error occurred»

So, this is pretty much a catch-all error exception handling for emails.

So, let’s now go into how to handle a specific email error.

Specific Email Exception Error Handling

So, let’s say we want to go a little more specifically into handling errors.

Let’s say we want to handle an error if the incorrect username-password combination was entered, which is a SMTPAuthenticationError.

So, the following code below will specifically handle an authentification error in the event that a wrong username-password combination was entered.

So, now in this code, we import the generic SMTPException class to handle any generic error that occurs, as well as the SMTPAuthenticationError class which handles an error with username-password combinations.

In our code, we have a try statement. This will execute if everything connects properly. In this case, the email will be sent.

If there is an error with the user authentication, then the line, «The username and/or password you entered is incorrect», will be output.

If there is any other type of error other than user authentication, the line, «An error occurred», will be output.

So, hopefully, this gives you a very good idea of how email exception error handling can be dealt with.

And you don’t have to simply print out a statement with exception handling. We’ve printed out statements above, but you literally can do anything. You can run the whole script all over if you have a backup email on file. For example, the user submitted 2 emails. The first was rejected, and so you run the whole script over with another email address. You can redirect the user to another page. The options are limitless.

And there are plenty of other specific errors that you could write scripts for, including SMTPConnectError, an error that occurs during establishment of a connection with the server.

There is SMTPServerDisconnected error, which is an error that is raised when the server unexpectedly disconnecxts, or when an attempt is made to use the SMTP instance before connecting it to a server.


email.errors : Exception and Defect classes¶

The following exception classes are defined in the email.errors module:

exception email.errors. MessageError В¶

This is the base class for all exceptions that the email package can raise. It is derived from the standard Exception class and defines no additional methods.

exception email.errors. MessageParseError В¶

This is the base class for exceptions raised by the Parser class. It is derived from MessageError . This class is also used internally by the parser used by headerregistry .

exception email.errors. HeaderParseError В¶

Raised under some error conditions when parsing the RFC 5322 headers of a message, this class is derived from MessageParseError . The set_boundary() method will raise this error if the content type is unknown when the method is called. Header may raise this error for certain base64 decoding errors, and when an attempt is made to create a header that appears to contain an embedded header (that is, there is what is supposed to be a continuation line that has no leading whitespace and looks like a header).

exception email.errors. BoundaryError В¶

Deprecated and no longer used.

exception email.errors. MultipartConversionError В¶

Raised when a payload is added to a Message object using add_payload() , but the payload is already a scalar and the message’s Content-Type main type is not either multipart or missing. MultipartConversionError multiply inherits from MessageError and the built-in TypeError .

Since Message.add_payload() is deprecated, this exception is rarely raised in practice. However the exception may also be raised if the attach() method is called on an instance of a class derived from MIMENonMultipart (e.g. MIMEImage ).

Here is the list of the defects that the FeedParser can find while parsing messages. Note that the defects are added to the message where the problem was found, so for example, if a message nested inside a multipart/alternative had a malformed header, that nested message object would have a defect, but the containing messages would not.

All defect classes are subclassed from email.errors.MessageDefect .

NoBoundaryInMultipartDefect – A message claimed to be a multipart, but had no boundary parameter.

StartBoundaryNotFoundDefect – The start boundary claimed in the Content-Type header was never found.

CloseBoundaryNotFoundDefect – A start boundary was found, but no corresponding close boundary was ever found.

New in version 3.3.

FirstHeaderLineIsContinuationDefect – The message had a continuation line as its first header line.

MisplacedEnvelopeHeaderDefect — A “Unix From” header was found in the middle of a header block.

Читайте также:  Slot2 detect eeprom error

MissingHeaderBodySeparatorDefect — A line was found while parsing headers that had no leading white space but contained no ‘:’. Parsing continues assuming that the line represents the first line of the body.

New in version 3.3.

MalformedHeaderDefect – A header was found that was missing a colon, or was otherwise malformed.

Deprecated since version 3.3: This defect has not been used for several Python versions.

MultipartInvariantViolationDefect – A message claimed to be a multipart, but no subparts were found. Note that when a message has this defect, its is_multipart() method may return False even though its content type claims to be multipart.

InvalidBase64PaddingDefect – When decoding a block of base64 encoded bytes, the padding was not correct. Enough padding is added to perform the decode, but the resulting decoded bytes may be invalid.

InvalidBase64CharactersDefect – When decoding a block of base64 encoded bytes, characters outside the base64 alphabet were encountered. The characters are ignored, but the resulting decoded bytes may be invalid.

InvalidBase64LengthDefect – When decoding a block of base64 encoded bytes, the number of non-padding base64 characters was invalid (1 more than a multiple of 4). The encoded block was kept as-is.

InvalidDateDefect – When decoding an invalid or unparsable date field. The original value is kept as-is.


smtplib — SMTP protocol client¶

Source code: Lib/

The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP operation, consult RFC 821 (Simple Mail Transfer Protocol) and RFC 1869 (SMTP Service Extensions).

Availability : not Emscripten, not WASI.

This module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi . See WebAssembly platforms for more information.

class smtplib. SMTP ( host=» , port=0 , local_hostname=None , [ timeout , ] source_address=None ) В¶

An SMTP instance encapsulates an SMTP connection. It has methods that support a full repertoire of SMTP and ESMTP operations. If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn() . If the connect() call returns anything other than a success code, an SMTPConnectError is raised. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). If the timeout expires, TimeoutError is raised. The optional source_address parameter allows binding to some specific source address in a machine with multiple network interfaces, and/or to some specific source TCP port. It takes a 2-tuple (host, port), for the socket to bind to as its source address before connecting. If omitted (or if host or port are » and/or 0 respectively) the OS default behavior will be used.

For normal use, you should only require the initialization/connect, sendmail() , and SMTP.quit() methods. An example is included below.

The SMTP class supports the with statement. When used like this, the SMTP QUIT command is issued automatically when the with statement exits. E.g.:

All commands will raise an auditing event smtplib.SMTP.send with arguments self and data , where data is the bytes about to be sent to the remote host.

Changed in version 3.3: Support for the with statement was added.

Changed in version 3.3: source_address argument was added.

New in version 3.5: The SMTPUTF8 extension ( RFC 6531) is now supported.

Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket

An SMTP_SSL instance behaves exactly the same as instances of SMTP . SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments local_hostname, timeout and source_address have the same meaning as they do in the SMTP class. context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. Please read Security considerations for best practices.

keyfile and certfile are a legacy alternative to context, and can point to a PEM formatted private key and certificate chain file for the SSL connection.

Changed in version 3.3: context was added.

Changed in version 3.3: source_address argument was added.

Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI ).

Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket

The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It’s common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. The optional arguments local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path for host, starting with a ‘/’.

Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don’t support or require any authentication, but your mileage might vary.

Changed in version 3.9: The optional timeout parameter was added.

A nice selection of exceptions is defined as well:

exception smtplib. SMTPException В¶

Subclass of OSError that is the base exception class for all the other exceptions provided by this module.

Changed in version 3.4: SMTPException became subclass of OSError

This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.

exception smtplib. SMTPResponseException В¶

Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.

exception smtplib. SMTPSenderRefused В¶

Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets ‘sender’ to the string that the SMTP server refused.

exception smtplib. SMTPRecipientsRefused В¶

All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients , which is a dictionary of exactly the same sort as SMTP.sendmail() returns.

Читайте также:  Script error function expected

exception smtplib. SMTPDataError В¶

The SMTP server refused to accept the message data.

exception smtplib. SMTPConnectError В¶

Error occurred during establishment of a connection with the server.

exception smtplib. SMTPHeloError В¶

The server refused our HELO message.

exception smtplib. SMTPNotSupportedError В¶

The command or option attempted is not supported by the server.

New in version 3.5.

SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.

RFC 821 — Simple Mail Transfer Protocol

Protocol definition for SMTP. This document covers the model, operating procedure, and protocol details for SMTP.

Definition of the ESMTP extensions for SMTP. This describes a framework for extending SMTP with new commands, supporting dynamic discovery of the commands provided by the server, and defines a few additional commands.

SMTP Objects¶

An SMTP instance has the following methods:

SMTP. set_debuglevel ( level ) В¶

Set the debug output level. A value of 1 or True for level results in debug messages for connection and for all messages sent to and received from the server. A value of 2 for level results in these messages being timestamped.

Changed in version 3.5: Added debuglevel 2.

Send a command cmd to the server. The optional argument args is simply concatenated to the command, separated by a space.

This returns a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)

In normal operation it should not be necessary to call this method explicitly. It is used to implement other methods and may be useful for testing private extensions.

If the connection to the server is lost while waiting for the reply, SMTPServerDisconnected will be raised.

SMTP. connect ( host = ‘localhost’ , port = 0 ) В¶

Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25). If the hostname ends with a colon ( ‘:’ ) followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This method is automatically invoked by the constructor if a host is specified during instantiation. Returns a 2-tuple of the response code and message sent by the server in its connection response.

Raises an auditing event smtplib.connect with arguments self , host , port .

Identify yourself to the SMTP server using HELO . The hostname argument defaults to the fully qualified domain name of the local host. The message returned by the server is stored as the helo_resp attribute of the object.

In normal operation it should not be necessary to call this method explicitly. It will be implicitly called by the sendmail() when necessary.

Identify yourself to an ESMTP server using EHLO . The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn() . Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to True or False depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).

Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary.

This method calls ehlo() and/or helo() if there has been no previous EHLO or HELO command this session. It tries ESMTP EHLO first.

The server didn’t reply properly to the HELO greeting.

SMTP. has_extn ( name ) В¶

Return True if name is in the set of SMTP service extensions returned by the server, False otherwise. Case is ignored.

SMTP. verify ( address ) В¶

Check the validity of an address on this server using SMTP VRFY . Returns a tuple consisting of code 250 and a full RFC 822 address (including human name) if the user address is valid. Otherwise returns an SMTP error code of 400 or greater and an error string.

Many sites disable SMTP VRFY in order to foil spammers.

Log in on an SMTP server that requires authentication. The arguments are the username and the password to authenticate with. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful, or may raise the following exceptions:

The server didn’t reply properly to the HELO greeting.

The server didn’t accept the username/password combination.

The AUTH command is not supported by the server.

No suitable authentication method was found.

Each of the authentication methods supported by smtplib are tried in turn if they are advertised as supported by the server. See auth() for a list of supported authentication methods. initial_response_ok is passed through to auth() .

Optional keyword argument initial_response_ok specifies whether, for authentication methods that support it, an “initial response” as specified in RFC 4954 can be sent along with the AUTH command, rather than requiring a challenge/response.

Changed in version 3.5: SMTPNotSupportedError may be raised, and the initial_response_ok parameter was added.

Issue an SMTP AUTH command for the specified authentication mechanism, and handle the challenge response via authobject.

mechanism specifies which authentication mechanism is to be used as argument to the AUTH command; the valid values are those listed in the auth element of esmtp_features .

authobject must be a callable object taking an optional single argument:

If optional keyword argument initial_response_ok is true, authobject() will be called first with no argument. It can return the RFC 4954 “initial response” ASCII str which will be encoded and sent with the AUTH command as below. If the authobject() does not support an initial response (e.g. because it requires a challenge), it should return None when called with challenge=None . If initial_response_ok is false, then authobject() will not be called first with None .

If the initial response check returns None , or if initial_response_ok is false, authobject() will be called to process the server’s challenge response; the challenge argument it is passed will be a bytes . It should return ASCII str data that will be base64 encoded and sent to the server.

The SMTP class provides authobjects for the CRAM-MD5 , PLAIN , and LOGIN mechanisms; they are named SMTP.auth_cram_md5 , SMTP.auth_plain , and SMTP.auth_login respectively. They all require that the user and password properties of the SMTP instance are set to appropriate values.

User code does not normally need to call auth directly, but can instead call the login() method, which will try each of the above mechanisms in turn, in the order listed. auth is exposed to facilitate the implementation of authentication methods not (or not yet) supported directly by smtplib .

Читайте также:  Make an error or commit an error

New in version 3.5.

Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.

If keyfile and certfile are provided, they are used to create an ssl.SSLContext .

Optional context parameter is an ssl.SSLContext object; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should be None .

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.

Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

The server didn’t reply properly to the HELO greeting.

The server does not support the STARTTLS extension.

SSL/TLS support is not available to your Python interpreter.

Changed in version 3.3: context was added.

Changed in version 3.4: The method now supports hostname check with SSLContext.check_hostname and Server Name Indicator (see HAS_SNI ).

Changed in version 3.5: The error raised for lack of STARTTLS support is now the SMTPNotSupportedError subclass instead of the base SMTPException .

Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime ) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail() , rcpt() and data() to send the message.)

The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. sendmail does not modify the message headers in any way.

msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it (if the option is in the feature set the server advertises). If EHLO fails, HELO will be tried and ESMTP options suppressed.

This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. That is, if this method does not raise an exception, then someone should get your mail. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

If SMTPUTF8 is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.

This method may raise the following exceptions:

All recipients were refused. Nobody got the mail. The recipients attribute of the exception object is a dictionary with information about the refused recipients (like the one returned when at least one recipient was accepted).

The server didn’t reply properly to the HELO greeting.

The server didn’t accept the from_addr.

The server replied with an unexpected error code (other than a refusal of a recipient).

SMTPUTF8 was given in the mail_options but is not supported by the server.

Unless otherwise noted, the connection will be open even after an exception is raised.

Changed in version 3.2: msg may be a byte string.

Changed in version 3.5: SMTPUTF8 support added, and SMTPNotSupportedError may be raised if SMTPUTF8 is specified but the server does not support it.

This is a convenience method for calling sendmail() with the message represented by an email.message.Message object. The arguments have the same meaning as for sendmail() , except that msg is a Message object.

If from_addr is None or to_addrs is None , send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. If the message contains more than one set of Resent-* headers, a ValueError is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.

send_message serializes msg using BytesGenerator with \r\n as the linesep, and calls sendmail() to transmit the resulting message. Regardless of the values of from_addr and to_addrs, send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg. If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise SMTPUTF8 support, an SMTPNotSupported error is raised. Otherwise the Message is serialized with a clone of its policy with the utf8 attribute set to True , and SMTPUTF8 and BODY=8BITMIME are added to mail_options.

New in version 3.2.

New in version 3.5: Support for internationalized addresses ( SMTPUTF8 ).

Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command.

Low-level methods corresponding to the standard SMTP/ESMTP commands HELP , RSET , NOOP , MAIL , RCPT , and DATA are also supported. Normally these do not need to be called directly, so they are not documented here. For details, consult the module code.

SMTP Example¶

This example prompts the user for addresses needed in the message envelope (‘To’ and ‘From’ addresses), and the message to be delivered. Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.

In general, you will want to use the email package’s features to construct an email message, which you can then send via send_message() ; see email: Examples .


Оцените статью