smtplib — SMTP protocol client¶
Source code:Lib/smtplib.py
Thesmtplib module defines an SMTP client session object that can be usedto send mail to any internet machine with an SMTP or ESMTP listener daemon. Fordetails of SMTP and ESMTP operation, consultRFC 821 (Simple Mail TransferProtocol) andRFC 1869 (SMTP Service Extensions).
Availability: not WASI.
This module does not work or is not available on WebAssembly. SeeWebAssembly platforms for more information.
- classsmtplib.SMTP(host='',port=0,local_hostname=None,[timeout,]source_address=None)¶
An
SMTPinstance encapsulates an SMTP connection. It has methodsthat support a full repertoire of SMTP and ESMTP operations. If the optionalhost andport parameters are given, the SMTPconnect()method iscalled with those parameters during initialization. If specified,local_hostname is used as the FQDN of the local host in the HELO/EHLOcommand. Otherwise, the local hostname is found usingsocket.getfqdn(). If theconnect()call returns anything otherthan a success code, anSMTPConnectErroris raised. The optionaltimeout parameter specifies a timeout in seconds for blocking operationslike the connection attempt (if not specified, the global default timeoutsetting will be used). If the timeout expires,TimeoutErrorisraised. The optionalsource_address parameter allows bindingto some specific source address in a machine with multiple networkinterfaces, 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 beforeconnecting. If omitted (or ifhost orport are''and/or0respectively) the OS default behavior will be used.For normal use, you should only require the initialization/connect,
sendmail(), andSMTP.quit()methods.An example is included below.The
SMTPclass supports thewithstatement. When usedlike this, the SMTPQUITcommand is issued automatically when thewithstatement exits. E.g.:>>>fromsmtplibimportSMTP>>>withSMTP("domain.org")assmtp:...smtp.noop()...(250, b'Ok')>>>
All commands will raise anauditing event
smtplib.SMTP.sendwith argumentsselfanddata,wheredatais the bytes about to be sent to the remote host.Changed in version 3.3:Support for the
withstatement was added.Changed in version 3.3:source_address argument was added.
Added in version 3.5:The SMTPUTF8 extension (RFC 6531) is now supported.
Changed in version 3.9:If thetimeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socket.
- classsmtplib.SMTP_SSL(host='',port=0,local_hostname=None,*,[timeout,]context=None,source_address=None)¶
An
SMTP_SSLinstance behaves exactly the same as instances ofSMTP.SMTP_SSLshould be used for situations where SSL isrequired from the beginning of the connection and usingstarttls()is not appropriate. Ifhost is not specified, the local host is used. Ifport is zero, the standard SMTP-over-SSL port (465) is used. The optionalargumentslocal_hostname,timeout andsource_address have the samemeaning as they do in theSMTPclass.context, also optional,can contain aSSLContextand allows configuring variousaspects of the secure connection. Please readSecurity considerations forbest practices.Changed in version 3.3:context was added.
Changed in version 3.3:Thesource_address argument was added.
Changed in version 3.4:The class now supports hostname check with
ssl.SSLContext.check_hostnameandServer Name Indication (seessl.HAS_SNI).Changed in version 3.9:If thetimeout parameter is set to be zero, it will raise a
ValueErrorto prevent the creation of a non-blocking socketChanged in version 3.12:The deprecatedkeyfile andcertfile parameters have been removed.
- classsmtplib.LMTP(host='',port=LMTP_PORT,local_hostname=None,source_address=None[,timeout])¶
The LMTP protocol, which is very similar to ESMTP, is heavily based on thestandard SMTP client. It’s common to use Unix sockets for LMTP, so our
connect()method must support that as well as a regular host:portserver. The optional argumentslocal_hostname andsource_address have thesame meaning as they do in theSMTPclass. To specify a Unixsocket, you must use an absolute path forhost, starting with a ‘/’.Authentication is supported, using the regular SMTP mechanism. When using aUnix socket, LMTP generally don’t support or require any authentication, butyour mileage might vary.
Changed in version 3.9:The optionaltimeout parameter was added.
A nice selection of exceptions is defined as well:
- exceptionsmtplib.SMTPException¶
Subclass of
OSErrorthat is the base exception class for allthe other exceptions provided by this module.Changed in version 3.4:SMTPException became subclass of
OSError
- exceptionsmtplib.SMTPServerDisconnected¶
This exception is raised when the server unexpectedly disconnects, or when anattempt is made to use the
SMTPinstance before connecting it to aserver.
- exceptionsmtplib.SMTPResponseException¶
Base class for all exceptions that include an SMTP error code. These exceptionsare generated in some instances when the SMTP server returns an error code.
- smtp_code¶
The error code.
- smtp_error¶
The error message.
- exceptionsmtplib.SMTPSenderRefused¶
Sender address refused. In addition to the attributes set by on all
SMTPResponseExceptionexceptions, this sets ‘sender’ to the string thatthe SMTP server refused.
- exceptionsmtplib.SMTPRecipientsRefused¶
All recipient addresses refused.
- recipients¶
A dictionary of exactly the same sort as returnedby
SMTP.sendmail()containing the errors foreach recipient.
- exceptionsmtplib.SMTPDataError¶
The SMTP server refused to accept the message data.
- exceptionsmtplib.SMTPConnectError¶
Error occurred during establishment of a connection with the server.
- exceptionsmtplib.SMTPHeloError¶
The server refused our
HELOmessage.
- exceptionsmtplib.SMTPNotSupportedError¶
The command or option attempted is not supported by the server.
Added in version 3.5.
- exceptionsmtplib.SMTPAuthenticationError¶
SMTP authentication went wrong. Most probably the server didn’t accept theusername/password combination provided.
See also
- RFC 821 - Simple Mail Transfer Protocol
Protocol definition for SMTP. This document covers the model, operatingprocedure, and protocol details for SMTP.
- RFC 1869 - SMTP Service Extensions
Definition of the ESMTP extensions for SMTP. This describes a framework forextending SMTP with new commands, supporting dynamic discovery of the commandsprovided by the server, and defines a few additional commands.
SMTP Objects¶
AnSMTP instance has the following methods:
- SMTP.set_debuglevel(level)¶
Set the debug output level. A value of 1 or
Trueforlevel results indebug messages for connection and for all messages sent to and received fromthe server. A value of 2 forlevel results in these messages beingtimestamped.Changed in version 3.5:Added debuglevel 2.
- SMTP.docmd(cmd,args='')¶
Send a commandcmd to the server. The optional argumentargs is simplyconcatenated to the command, separated by a space.
This returns a 2-tuple composed of a numeric response code and the actualresponse 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 privateextensions.
If the connection to the server is lost while waiting for the reply,
SMTPServerDisconnectedwill be raised.
- SMTP.connect(host='localhost',port=0)¶
Connect to a host on a given port. The defaults are to connect to the localhost 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 numberinterpreted as the port number to use. This method is automatically invoked bythe constructor if a host is specified during instantiation. Returns a2-tuple of the response code and message sent by the server in itsconnection response.Raises anauditing event
smtplib.connectwith argumentsself,host,port.
- SMTP.helo(name='')¶
Identify yourself to the SMTP server using
HELO. The hostname argumentdefaults to the fully qualified domain name of the local host.The message returned by the server is stored as thehelo_respattributeof 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.
- SMTP.ehlo(name='')¶
Identify yourself to an ESMTP server using
EHLO. The hostname argumentdefaults to the fully qualified domain name of the local host. Examine theresponse for ESMTP option and store them for use byhas_extn().Also sets several informational attributes: the message returned bythe server is stored as theehlo_respattribute,does_esmtpis set toTrueorFalsedepending on whether the server supportsESMTP, andesmtp_featureswill be a dictionary containing the namesof 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 benecessary to call this method explicitly. It will be implicitly called bysendmail()when necessary.
- SMTP.ehlo_or_helo_if_needed()¶
This method calls
ehlo()and/orhelo()if there has been nopreviousEHLOorHELOcommand this session. It tries ESMTPEHLOfirst.SMTPHeloErrorThe server didn’t reply properly to the
HELOgreeting.
- SMTP.has_extn(name)¶
Return
Trueifname is in the set of SMTP service extensions returnedby the server,Falseotherwise. Case is ignored.
- SMTP.verify(address)¶
Check the validity of an address on this server using SMTP
VRFY. Returns atuple consisting of code 250 and a fullRFC 822 address (including humanname) if the user address is valid. Otherwise returns an SMTP error code of 400or greater and an error string.Note
Many sites disable SMTP
VRFYin order to foil spammers.
- SMTP.login(user,password,*,initial_response_ok=True)¶
Log in on an SMTP server that requires authentication. The arguments are theusername and the password to authenticate with. If there has been no previous
EHLOorHELOcommand this session, this method tries ESMTPEHLOfirst. This method will return normally if the authentication was successful, ormay raise the following exceptions:SMTPHeloErrorThe server didn’t reply properly to the
HELOgreeting.SMTPAuthenticationErrorThe server didn’t accept the username/password combination.
SMTPNotSupportedErrorThe
AUTHcommand is not supported by the server.SMTPExceptionNo suitable authentication method was found.
Each of the authentication methods supported by
smtplibare tried inturn if they are advertised as supported by the server. Seeauth()for a list of supported authentication methods.initial_response_ok ispassed through toauth().Optional keyword argumentinitial_response_ok specifies whether, forauthentication methods that support it, an “initial response” as specifiedinRFC 4954 can be sent along with the
AUTHcommand, rather thanrequiring a challenge/response.Changed in version 3.5:
SMTPNotSupportedErrormay be raised, and theinitial_response_ok parameter was added.
- SMTP.auth(mechanism,authobject,*,initial_response_ok=True)¶
Issue an
SMTPAUTHcommand for the specified authenticationmechanism, and handle the challenge response viaauthobject.mechanism specifies which authentication mechanism is tobe used as argument to the
AUTHcommand; the valid values arethose listed in theauthelement ofesmtp_features.authobject must be a callable object taking an optional single argument:
data=authobject(challenge=None)
If optional keyword argumentinitial_response_ok is true,
authobject()will be called first with no argument. It can return theRFC 4954 “initial response” ASCIIstrwhich will be encoded and sent withtheAUTHcommand as below. If theauthobject()does not support aninitial response (e.g. because it requires a challenge), it should returnNonewhen called withchallenge=None. Ifinitial_response_ok isfalse, thenauthobject()will not be called first withNone.If the initial response check returns
None, or ifinitial_response_ok isfalse,authobject()will be called to process the server’s challengeresponse; thechallenge argument it is passed will be abytes. Itshould return ASCIIstrdata that will be base64 encoded and sent to theserver.The
SMTPclass providesauthobjectsfor theCRAM-MD5,PLAIN,andLOGINmechanisms; they are namedSMTP.auth_cram_md5,SMTP.auth_plain, andSMTP.auth_loginrespectively. They all requirethat theuserandpasswordproperties of theSMTPinstance areset to appropriate values.User code does not normally need to call
authdirectly, but can insteadcall thelogin()method, which will try each of the above mechanismsin turn, in the order listed.authis exposed to facilitate theimplementation of authentication methods not (or not yet) supporteddirectly bysmtplib.Added in version 3.5.
- SMTP.starttls(*,context=None)¶
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTPcommands that follow will be encrypted. You should then call
ehlo()again.Ifkeyfile andcertfile are provided, they are used to create an
ssl.SSLContext.Optionalcontext parameter is an
ssl.SSLContextobject; This isan alternative to using a keyfile and a certfile and if specified bothkeyfile andcertfile should beNone.If there has been no previous
EHLOorHELOcommand this session,this method tries ESMTPEHLOfirst.Changed in version 3.12:The deprecatedkeyfile andcertfile parameters have been removed.
SMTPHeloErrorThe server didn’t reply properly to the
HELOgreeting.SMTPNotSupportedErrorThe server does not support the STARTTLS extension.
RuntimeErrorSSL/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
ssl.SSLContext.check_hostnameandServer Name Indicator (seeHAS_SNI).Changed in version 3.5:The error raised for lack of STARTTLS support is now the
SMTPNotSupportedErrorsubclass instead of the baseSMTPException.
- SMTP.sendmail(from_addr,to_addrs,msg,mail_options=(),rcpt_options=())¶
Send mail. The required arguments are anRFC 822 from-address string, a listofRFC 822 to-address strings (a bare string will be treated as a list with 1address), and a message string. The caller may pass a list of ESMTP options(such as
8bitmime) to be used inMAILFROMcommands asmail_options.ESMTP options (such asDSNcommands) that should be used with allRCPTcommands can be passed asrcpt_options. (If you need to use different ESMTPoptions to different recipients you have to use the low-level methods such asmail(),rcpt()anddata()to send the message.)Note
Thefrom_addr andto_addrs parameters are used to construct the messageenvelope used by the transport agents.
sendmaildoes not modify themessage headers in any way.msg may be a string containing characters in the ASCII range, or a bytestring. A string is encoded to bytes using the ascii codec, and lone
\rand\ncharacters are converted to\r\ncharacters. A byte string isnot modified.If there has been no previous
EHLOorHELOcommand this session, thismethod tries ESMTPEHLOfirst. If the server does ESMTP, message size andeach of the specified options will be passed to it (if the option is in thefeature set the server advertises). IfEHLOfails,HELOwill be triedand ESMTP options suppressed.This method will return normally if the mail is accepted for at least onerecipient. Otherwise it will raise an exception. That is, if this method doesnot raise an exception, then someone should get your mail. If this method doesnot raise an exception, it returns a dictionary, with one entry for eachrecipient that was refused. Each entry contains a tuple of the SMTP error codeand the accompanying error message sent by the server.
If
SMTPUTF8is included inmail_options, and the server supports it,from_addr andto_addrs may contain non-ASCII characters.This method may raise the following exceptions:
SMTPRecipientsRefusedAll recipients were refused. Nobody got the mail.
SMTPHeloErrorThe server didn’t reply properly to the
HELOgreeting.SMTPSenderRefusedThe server didn’t accept thefrom_addr.
SMTPDataErrorThe server replied with an unexpected error code (other than a refusal of arecipient).
SMTPNotSupportedErrorSMTPUTF8was given in themail_options but is not supported by theserver.
Unless otherwise noted, the connection will be open even after an exception israised.
Changed in version 3.2:msg may be a byte string.
Changed in version 3.5:
SMTPUTF8support added, andSMTPNotSupportedErrormay beraised ifSMTPUTF8is specified but the server does not support it.
- SMTP.send_message(msg,from_addr=None,to_addrs=None,mail_options=(),rcpt_options=())¶
This is a convenience method for calling
sendmail()with the messagerepresented by anemail.message.Messageobject. The arguments havethe same meaning as forsendmail(), except thatmsg is aMessageobject.Iffrom_addr is
Noneorto_addrs isNone,send_messagefillsthose arguments with addresses extracted from the headers ofmsg asspecified inRFC 5322:from_addr is set to theSenderfield if it is present, and otherwise to theFrom field.to_addrs combines the values (if any) of theTo,Cc, andBcc fields frommsg. If exactly oneset ofResent-* headers appear in the message, the regularheaders are ignored and theResent-* headers are used instead.If the message contains more than one set ofResent-* headers,aValueErroris raised, since there is no way to unambiguously detectthe most recent set ofResent- headers.send_messageserializesmsg usingBytesGeneratorwith\r\nas thelinesep, andcallssendmail()to transmit the resulting message. Regardless of thevalues offrom_addr andto_addrs,send_messagedoes not transmit anyBcc orResent-Bcc headers that may appearinmsg. If any of the addresses infrom_addr andto_addrs containnon-ASCII characters and the server does not advertiseSMTPUTF8support,anSMTPNotSupportedErroris raised. Otherwise theMessageisserialized with a clone of itspolicywith theutf8attribute set toTrue, andSMTPUTF8andBODY=8BITMIMEare added tomail_options.Added in version 3.2.
Added in version 3.5:Support for internationalized addresses (
SMTPUTF8).
- SMTP.quit()¶
Terminate the SMTP session and close the connection. Return the result ofthe SMTP
QUITcommand.
Low-level methods corresponding to the standard SMTP/ESMTP commandsHELP,RSET,NOOP,MAIL,RCPT, andDATA are also supported.Normally these do not need to be called directly, so they are not documentedhere. For details, consult the module code.
Additionally, an SMTP instance has the following attributes:
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 headersto be included with the message must be included in the message as entered; thisexample doesn’t do any processing of theRFC 822 headers. In particular, the‘To’ and ‘From’ addresses must be included in the message headers explicitly:
importsmtplibdefprompt(title):returninput(title).strip()from_addr=prompt("From: ")to_addrs=prompt("To: ").split()print("Enter message, end with ^D (Unix) or ^Z (Windows):")# Add the From: and To: headers at the start!lines=[f"From:{from_addr}",f"To:{', '.join(to_addrs)}",""]whileTrue:try:line=input()exceptEOFError:breakelse:lines.append(line)msg="\r\n".join(lines)print("Message length is",len(msg))server=smtplib.SMTP("localhost")server.set_debuglevel(1)server.sendmail(from_addr,to_addrs,msg)server.quit()
Note
In general, you will want to use theemail package’s features toconstruct an email message, which you can then sendviasend_message(); seeemail: Examples.