3 '''SMTP/ESMTP client class.
5 This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
9 Please remember, when doing ESMTP, that the names of the SMTP service
10 extensions are NOT the same thing as the option keywords for the RCPT
16 >>> s=smtplib.SMTP("localhost")
18 This is Sendmail version 8.8.4
20 HELO EHLO MAIL RCPT DATA
21 RSET NOOP QUIT HELP VRFY
23 For more info use "HELP <topic>".
24 To report bugs in the implementation send email to
25 sendmail-bugs@sendmail.org.
26 For local information send email to Postmaster at your site.
28 >>> s.putcmd("vrfy","someone@here")
30 (250, "Somebody OverHere <somebody@here.my.org>")
34 # Author: The Dragon De Monsyne <dragondm@integral.org>
35 # ESMTP support, test code and doc fixes added by
36 # Eric S. Raymond <esr@thyrsus.com>
37 # Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
38 # by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
40 # This was modified from the Python 1.5 library HTTP lib.
51 # Exception classes used by this module.
52 class SMTPException(Exception):
53 """Base class for all exceptions raised by this module."""
55 class SMTPServerDisconnected(SMTPException
):
56 """Not connected to any SMTP server.
58 This exception is raised when the server unexpectedly disconnects,
59 or when an attempt is made to use the SMTP instance before
60 connecting it to a server.
63 class SMTPResponseException(SMTPException
):
64 """Base class for all exceptions that include an SMTP error code.
66 These exceptions are generated in some instances when the SMTP
67 server returns an error code. The error code is stored in the
68 `smtp_code' attribute of the error, and the `smtp_error' attribute
69 is set to the error message.
72 def __init__(self
, code
, msg
):
75 self
.args
= (code
, msg
)
77 class SMTPSenderRefused(SMTPResponseException
):
78 """Sender address refused.
79 In addition to the attributes set by on all SMTPResponseException
80 exceptions, this sets `sender' to the string that the SMTP refused.
83 def __init__(self
, code
, msg
, sender
):
87 self
.args
= (code
, msg
, sender
)
89 class SMTPRecipientsRefused(SMTPException
):
90 """All recipient addresses refused.
91 The errors for each recipient are accessible through the attribute
92 'recipients', which is a dictionary of exactly the same sort as
93 SMTP.sendmail() returns.
96 def __init__(self
, recipients
):
97 self
.recipients
= recipients
98 self
.args
= ( recipients
,)
101 class SMTPDataError(SMTPResponseException
):
102 """The SMTP server didn't accept the data."""
104 class SMTPConnectError(SMTPResponseException
):
105 """Error during connection establishment."""
107 class SMTPHeloError(SMTPResponseException
):
108 """The server refused our HELO reply."""
112 """Quote a subset of the email addresses defined by RFC 821.
114 Should be able to handle anything rfc822.parseaddr can handle.
118 m
=rfc822
.parseaddr(addr
)[1]
119 except AttributeError:
122 #something weird here.. punt -ddm
128 """Quote data for email.
130 Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
131 Internet CRLF end-of-line.
133 return re
.sub(r
'(?m)^\.', '..',
134 re
.sub(r
'(?:\r\n|\n|\r(?!\n))', CRLF
, data
))
136 def _get_fqdn_hostname(name
):
137 name
= string
.strip(name
)
139 name
= socket
.gethostname()
141 hostname
, aliases
, ipaddrs
= socket
.gethostbyaddr(name
)
145 aliases
.insert(0, hostname
)
155 """This class manages a connection to an SMTP or ESMTP server.
157 SMTP objects have the following attributes:
159 This is the message given by the server in response to the
160 most recent HELO command.
163 This is the message given by the server in response to the
164 most recent EHLO command. This is usually multiline.
167 This is a True value _after you do an EHLO command_, if the
168 server supports ESMTP.
171 This is a dictionary, which, if the server supports ESMTP,
172 will _after you do an EHLO command_, contain the names of the
173 SMTP service extensions this server supports, and their
176 Note, all extension names are mapped to lower case in the
179 See each method's docstrings for details. In general, there is a
180 method of the same name to perform each SMTP command. There is also a
181 method called 'sendmail' that will do an entire mail transaction.
189 def __init__(self
, host
= '', port
= 0):
190 """Initialize a new instance.
192 If specified, `host' is the name of the remote host to which to
193 connect. If specified, `port' specifies the port to which to connect.
194 By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
195 if the specified `host' doesn't respond correctly.
198 self
.esmtp_features
= {}
200 (code
, msg
) = self
.connect(host
, port
)
202 raise SMTPConnectError(code
, msg
)
204 def set_debuglevel(self
, debuglevel
):
205 """Set the debug output level.
207 A non-false value results in debug messages for connection and for all
208 messages sent to and received from the server.
211 self
.debuglevel
= debuglevel
213 def connect(self
, host
='localhost', port
= 0):
214 """Connect to a host on a given port.
216 If the hostname ends with a colon (`:') followed by a number, and
217 there is no port specified, that suffix will be stripped off and the
218 number interpreted as the port number to use.
220 Note: This method is automatically invoked by __init__, if a host is
221 specified during instantiation.
225 i
= string
.find(host
, ':')
227 host
, port
= host
[:i
], host
[i
+1:]
228 try: port
= string
.atoi(port
)
229 except string
.atoi_error
:
230 raise socket
.error
, "nonnumeric port"
231 if not port
: port
= SMTP_PORT
232 self
.sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
233 if self
.debuglevel
> 0: print 'connect:', (host
, port
)
234 self
.sock
.connect((host
, port
))
235 (code
,msg
)=self
.getreply()
236 if self
.debuglevel
>0 : print "connect:", msg
240 """Send `str' to the server."""
241 if self
.debuglevel
> 0: print 'send:', `
str`
246 raise SMTPServerDisconnected('Server not connected')
248 raise SMTPServerDisconnected('please run connect() first')
250 def putcmd(self
, cmd
, args
=""):
251 """Send a command to the server."""
253 str = '%s%s' % (cmd
, CRLF
)
255 str = '%s %s%s' % (cmd
, args
, CRLF
)
259 """Get a reply from the server.
261 Returns a tuple consisting of:
263 - server response code (e.g. '250', or such, if all goes well)
264 Note: returns -1 if it can't read response code.
266 - server response string corresponding to response code (multiline
267 responses are converted to a single, multiline string).
269 Raises SMTPServerDisconnected if end-of-file is reached.
272 if self
.file is None:
273 self
.file = self
.sock
.makefile('rb')
275 line
= self
.file.readline()
278 raise SMTPServerDisconnected("Connection unexpectedly closed")
279 if self
.debuglevel
> 0: print 'reply:', `line`
280 resp
.append(string
.strip(line
[4:]))
282 # Check that the error code is syntactically correct.
283 # Don't attempt to read a continuation line if it is broken.
285 errcode
= string
.atoi(code
)
289 # Check if multiline response.
293 errmsg
= string
.join(resp
,"\n")
294 if self
.debuglevel
> 0:
295 print 'reply: retcode (%s); Msg: %s' % (errcode
,errmsg
)
296 return errcode
, errmsg
298 def docmd(self
, cmd
, args
=""):
299 """Send a command, and return its response code."""
300 self
.putcmd(cmd
,args
)
301 return self
.getreply()
304 def helo(self
, name
=''):
305 """SMTP 'helo' command.
306 Hostname to send for this command defaults to the FQDN of the local
309 self
.putcmd("helo", _get_fqdn_hostname(name
))
310 (code
,msg
)=self
.getreply()
314 def ehlo(self
, name
=''):
315 """ SMTP 'ehlo' command.
316 Hostname to send for this command defaults to the FQDN of the local
319 self
.putcmd("ehlo", _get_fqdn_hostname(name
))
320 (code
,msg
)=self
.getreply()
321 # According to RFC1869 some (badly written)
322 # MTA's will disconnect on an ehlo. Toss an exception if
324 if code
== -1 and len(msg
) == 0:
325 raise SMTPServerDisconnected("Server not connected")
330 #parse the ehlo response -ddm
331 resp
=string
.split(self
.ehlo_resp
,'\n')
334 m
=re
.match(r
'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each
)
336 feature
=string
.lower(m
.group("feature"))
337 params
=string
.strip(m
.string
[m
.end("feature"):])
338 self
.esmtp_features
[feature
]=params
341 def has_extn(self
, opt
):
342 """Does the server support a given SMTP service extension?"""
343 return self
.esmtp_features
.has_key(string
.lower(opt
))
345 def help(self
, args
=''):
346 """SMTP 'help' command.
347 Returns help text from server."""
348 self
.putcmd("help", args
)
349 return self
.getreply()
352 """SMTP 'rset' command -- resets session."""
353 return self
.docmd("rset")
356 """SMTP 'noop' command -- doesn't do anything :>"""
357 return self
.docmd("noop")
359 def mail(self
,sender
,options
=[]):
360 """SMTP 'mail' command -- begins mail xfer session."""
362 if options
and self
.does_esmtp
:
363 optionlist
= ' ' + string
.join(options
, ' ')
364 self
.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender
) ,optionlist
))
365 return self
.getreply()
367 def rcpt(self
,recip
,options
=[]):
368 """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
370 if options
and self
.does_esmtp
:
371 optionlist
= ' ' + string
.join(options
, ' ')
372 self
.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip
),optionlist
))
373 return self
.getreply()
376 """SMTP 'DATA' command -- sends message data to server.
378 Automatically quotes lines beginning with a period per rfc821.
379 Raises SMTPDataError if there is an unexpected reply to the
380 DATA command; the return value from this method is the final
381 response code received when the all data is sent.
384 (code
,repl
)=self
.getreply()
385 if self
.debuglevel
>0 : print "data:", (code
,repl
)
387 raise SMTPDataError(code
,repl
)
394 (code
,msg
)=self
.getreply()
395 if self
.debuglevel
>0 : print "data:", (code
,msg
)
398 def verify(self
, address
):
399 """SMTP 'verify' command -- checks for address validity."""
400 self
.putcmd("vrfy", quoteaddr(address
))
401 return self
.getreply()
405 def expn(self
, address
):
406 """SMTP 'verify' command -- checks for address validity."""
407 self
.putcmd("expn", quoteaddr(address
))
408 return self
.getreply()
410 # some useful methods
411 def sendmail(self
, from_addr
, to_addrs
, msg
, mail_options
=[],
413 """This command performs an entire mail transaction.
416 - from_addr : The address sending this mail.
417 - to_addrs : A list of addresses to send this mail to. A bare
418 string will be treated as a list with 1 address.
419 - msg : The message to send.
420 - mail_options : List of ESMTP options (such as 8bitmime) for the
422 - rcpt_options : List of ESMTP options (such as DSN commands) for
423 all the rcpt commands.
425 If there has been no previous EHLO or HELO command this session, this
426 method tries ESMTP EHLO first. If the server does ESMTP, message size
427 and each of the specified options will be passed to it. If EHLO
428 fails, HELO will be tried and ESMTP options suppressed.
430 This method will return normally if the mail is accepted for at least
431 one recipient. It returns a dictionary, with one entry for each
432 recipient that was refused. Each entry contains a tuple of the SMTP
433 error code and the accompanying error message sent by the server.
435 This method may raise the following exceptions:
437 SMTPHeloError The server didn't reply properly to
439 SMTPRecipientsRefused The server rejected ALL recipients
441 SMTPSenderRefused The server didn't accept the from_addr.
442 SMTPDataError The server replied with an unexpected
443 error code (other than a refusal of
446 Note: the connection will be open even after an exception is raised.
451 >>> s=smtplib.SMTP("localhost")
452 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
455 ... Subject: testin'...
457 ... This is a test '''
458 >>> s.sendmail("me@my.org",tolist,msg)
459 { "three@three.org" : ( 550 ,"User unknown" ) }
462 In the above example, the message was accepted for delivery to three
463 of the four addresses, and one was rejected, with the error code
464 550. If all addresses are accepted, then the method will return an
468 if self
.helo_resp
is None and self
.ehlo_resp
is None:
469 if not (200 <= self
.ehlo()[0] <= 299):
470 (code
,resp
) = self
.helo()
471 if not (200 <= code
<= 299):
472 raise SMTPHeloError(code
, resp
)
475 # Hmmm? what's this? -ddm
476 # self.esmtp_features['7bit']=""
477 if self
.has_extn('size'):
478 esmtp_opts
.append("size=" + `
len(msg
)`
)
479 for option
in mail_options
:
480 esmtp_opts
.append(option
)
482 (code
,resp
) = self
.mail(from_addr
, esmtp_opts
)
485 raise SMTPSenderRefused(code
, resp
, from_addr
)
487 if type(to_addrs
) == types
.StringType
:
488 to_addrs
= [to_addrs
]
489 for each
in to_addrs
:
490 (code
,resp
)=self
.rcpt(each
, rcpt_options
)
491 if (code
<> 250) and (code
<> 251):
492 senderrs
[each
]=(code
,resp
)
493 if len(senderrs
)==len(to_addrs
):
494 # the server refused all our recipients
496 raise SMTPRecipientsRefused(senderrs
)
497 (code
,resp
)=self
.data(msg
)
500 raise SMTPDataError(code
, resp
)
501 #if we got here then somebody got our mail
506 """Close the connection to the SMTP server."""
516 """Terminate the SMTP session."""
521 # Test the sendmail method, which tests most of the others.
522 # Note: This always sends to localhost.
523 if __name__
== '__main__':
527 sys
.stdout
.write(prompt
+ ": ")
528 return string
.strip(sys
.stdin
.readline())
530 fromaddr
= prompt("From")
531 toaddrs
= string
.splitfields(prompt("To"), ',')
532 print "Enter message, end with ^D:"
535 line
= sys
.stdin
.readline()
539 print "Message length is " + `
len(msg
)`
541 server
= SMTP('localhost')
542 server
.set_debuglevel(1)
543 server
.sendmail(fromaddr
, toaddrs
, msg
)