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).
ASMTP instance encapsulates an SMTP connection. It has methodsthat support a full repertoire of SMTP and ESMTP operations. If the optionalhost and port 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, anSMTPConnectError is 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). The optional source_address parameter allows to bindto 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 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(), andquit() methods.An example is included below.
TheSMTP class supports thewith statement. When usedlike this, the SMTPQUIT command is issued automatically when thewith statement exits. E.g.:
>>>fromsmtplibimportSMTP>>>withSMTP("domain.org")assmtp:...smtp.noop()...(250, b'Ok')>>>
Changed in version 3.3:Support for thewith statement was added.
Changed in version 3.3:source_address argument was added.
ASMTP_SSL instance behaves exactly the same as instances ofSMTP.SMTP_SSL should be used for situations where SSL isrequired from the beginning of the connection and usingstarttls() isnot 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 andsource_address have the same meaning asthey do in theSMTP class.keyfile andcertfile are alsooptional, and can contain a PEM formatted private key and certificate chainfile for the SSL connection.context also optional, can contain aSSLContext, and is an alternative to keyfile and certfile; If it isspecified both keyfile and certfile must be None. The optionaltimeoutparameter specifies a timeout in seconds for blocking operations like theconnection attempt (if not specified, the global default timeout settingwill be used). The optional source_address parameter allows to bind to somespecific 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. Ifomitted (or if host or port are'' and/or 0 respectively) the OS defaultbehavior will be used.
Changed in version 3.3:context was added.
Changed in version 3.3:source_address argument was added.
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 ourconnect() method must support that as well as a regular host:portserver. The optional arguments local_hostname and source_address have thesame meaning as they do in theSMTP class. 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.
A nice selection of exceptions is defined as well:
The base exception class for all the other exceptions provided by thismodule.
This exception is raised when the server unexpectedly disconnects, or when anattempt is made to use theSMTP instance before connecting it to aserver.
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. Theerror code is stored in thesmtp_code attribute of the error, and thesmtp_error attribute is set to the error message.
Sender address refused. In addition to the attributes set by on allSMTPResponseException exceptions, this sets ‘sender’ to the string thatthe SMTP server refused.
All recipient addresses refused. The errors for each recipient are accessiblethrough the attributerecipients, which is a dictionary of exactly thesame sort asSMTP.sendmail() returns.
The SMTP server refused to accept the message data.
Error occurred during establishment of a connection with the server.
The server refused ourHELO message.
SMTP authentication went wrong. Most probably the server didn’t accept theusername/password combination provided.
See also
AnSMTP instance has the following methods:
Set the debug output level. A true value forlevel results in debug messagesfor connection and for all messages sent to and received from the server.
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,SMTPServerDisconnected will be raised.
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.
Identify yourself to the SMTP server usingHELO. The hostname argumentdefaults to the fully qualified domain name of the local host.The message returned by the server is stored as thehelo_resp attributeof the object.
In normal operation it should not be necessary to call this method explicitly.It will be implicitly called by thesendmail() when necessary.
Identify yourself to an ESMTP server usingEHLO. 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_resp attribute,does_esmtpis set to true or false depending on whether the server supports ESMTP, andesmtp_features will be a dictionary containing the names of theSMTP service extensions this server supports, and theirparameters (if any).
Unless you wish to usehas_extn() before sending mail, it should not benecessary to call this method explicitly. It will be implicitly called bysendmail() when necessary.
This method callehlo() and orhelo() if there has been nopreviousEHLO orHELO command this session. It tries ESMTPEHLOfirst.
ReturnTrue ifname is in the set of SMTP service extensions returnedby the server,False otherwise. Case is ignored.
Check the validity of an address on this server using SMTPVRFY. 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 SMTPVRFY in order to foil spammers.
Log in on an SMTP server that requires authentication. The arguments are theusername and the password to authenticate with. If there has been no previousEHLO orHELO command this session, this method tries ESMTPEHLOfirst. This method will return normally if the authentication was successful, ormay raise the following exceptions:
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTPcommands that follow will be encrypted. You should then callehlo()again.
Ifkeyfile andcertfile are provided, these are passed to thesocketmodule’sssl() function.
Optionalcontext parameter is assl.SSLContext object; This is an alternative tousing a keyfile and a certfile and if specified bothkeyfile andcertfile should be None.
If there has been no previousEHLO orHELO command this session,this method tries ESMTPEHLO first.
Changed in version 3.3:context was added.
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 as8bitmime) to be used inMAILFROM commands asmail_options.ESMTP options (such asDSN commands) 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.sendmail does 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\n characters are converted to\r\n characters. A byte string isnot modified.
If there has been no previousEHLO orHELO command this session, thismethod tries ESMTPEHLO first. 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). IfEHLO fails,HELO will 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.
This method may raise the following exceptions:
Unless otherwise noted, the connection will be open even after an exception israised.
Changed in version 3.2:msg may be a byte string.
This is a convenience method for callingsendmail() with the messagerepresented by anemail.message.Message object. The arguments havethe same meaning as forsendmail(), except thatmsg is aMessageobject.
Iffrom_addr isNone orto_addrs isNone,send_message fillsthose arguments with addresses extracted from the headers ofmsg asspecified inRFC 2822:from_addr is set to theSenderfield if it is present, and otherwise to theFrom field.to_adresses 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,aValueError is raised, since there is no way to unambiguously detectthe most recent set ofResent- headers.
send_message serializesmsg usingBytesGenerator with\r\n as thelinesep, andcallssendmail() to transmit the resulting message. Regardless of thevalues offrom_addr andto_addrs,send_message does not transmit anyBcc orResent-Bcc headers that may appearinmsg.
New in version 3.2.
Terminate the SMTP session and close the connection. Return the result ofthe SMTPQUIT command.
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.
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(prompt):returninput(prompt).strip()fromaddr=prompt("From: ")toaddrs=prompt("To: ").split()print("Enter message, end with ^D (Unix) or ^Z (Windows):")# Add the From: and To: headers at the start!msg=("From: %s\r\nTo: %s\r\n\r\n"%(fromaddr,", ".join(toaddrs)))whileTrue:try:line=input()exceptEOFError:breakifnotline:breakmsg=msg+lineprint("Message length is",len(msg))server=smtplib.SMTP('localhost')server.set_debuglevel(1)server.sendmail(fromaddr,toaddrs,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.
21.16.nntplib — NNTP protocol client
Enter search terms or a module, class or function name.