blob: 47e1fafbb3d9570f12b6a8d4acfe20a249605248 [file] [log] [blame]
Barry Warsaw4c4bec81998-12-22 03:02:20 +00001#! /usr/bin/env python
2
3'''SMTP/ESMTP client class.
Guido van Rossumbbe323e1998-01-29 17:24:40 +00004
5Author: The Dragon De Monsyne <dragondm@integral.org>
Guido van Rossum95e6f701998-06-25 02:15:50 +00006ESMTP support, test code and doc fixes added by
Guido van Rossumfcfb6321998-08-04 15:29:54 +00007 Eric S. Raymond <esr@thyrsus.com>
Guido van Rossum69a79bc1998-07-13 15:18:49 +00008Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
Guido van Rossumfcfb6321998-08-04 15:29:54 +00009 by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
10
Barry Warsawa7d9bdf1998-12-22 03:24:27 +000011This was modified from the Python 1.5 library HTTP lib.
Guido van Rossumbbe323e1998-01-29 17:24:40 +000012
Guido van Rossum95e6f701998-06-25 02:15:50 +000013This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
Guido van Rossumbbe323e1998-01-29 17:24:40 +000014
Guido van Rossumfcfb6321998-08-04 15:29:54 +000015Notes:
16
17Please remember, when doing ESMTP, that the names of the SMTP service
Barry Warsaw4c4bec81998-12-22 03:02:20 +000018extensions are NOT the same thing as the option keywords for the RCPT
Guido van Rossumfcfb6321998-08-04 15:29:54 +000019and MAIL commands!
20
Guido van Rossumbbe323e1998-01-29 17:24:40 +000021Example:
22
Barry Warsawa7d9bdf1998-12-22 03:24:27 +000023 >>> import smtplib
24 >>> s=smtplib.SMTP("localhost")
25 >>> print s.help()
26 This is Sendmail version 8.8.4
27 Topics:
28 HELO EHLO MAIL RCPT DATA
29 RSET NOOP QUIT HELP VRFY
30 EXPN VERB ETRN DSN
31 For more info use "HELP <topic>".
32 To report bugs in the implementation send email to
33 sendmail-bugs@sendmail.org.
34 For local information send email to Postmaster at your site.
35 End of HELP info
36 >>> s.putcmd("vrfy","someone@here")
37 >>> s.getreply()
38 (250, "Somebody OverHere <somebody@here.my.org>")
39 >>> s.quit()
Barry Warsaw4c4bec81998-12-22 03:02:20 +000040'''
Guido van Rossumbbe323e1998-01-29 17:24:40 +000041
42import socket
Barry Warsaw07201771998-12-22 20:37:36 +000043import string
44import re
Guido van Rossumfcfb6321998-08-04 15:29:54 +000045import rfc822
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +000046import types
Guido van Rossumbbe323e1998-01-29 17:24:40 +000047
48SMTP_PORT = 25
49CRLF="\r\n"
50
51# used for exceptions
Guido van Rossum40233ea1999-01-15 03:23:55 +000052class SMTPException(Exception): pass
53class SMTPServerDisconnected(SMTPException): pass
54class SMTPSenderRefused(SMTPException): pass
55class SMTPRecipientsRefused(SMTPException): pass
56class SMTPDataError(SMTPException): pass
Guido van Rossumbbe323e1998-01-29 17:24:40 +000057
Guido van Rossum69a79bc1998-07-13 15:18:49 +000058def quoteaddr(addr):
59 """Quote a subset of the email addresses defined by RFC 821.
60
Barry Warsawa7d9bdf1998-12-22 03:24:27 +000061 Should be able to handle anything rfc822.parseaddr can handle.
62 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +000063 m=None
Guido van Rossum69a79bc1998-07-13 15:18:49 +000064 try:
Guido van Rossumfcfb6321998-08-04 15:29:54 +000065 m=rfc822.parseaddr(addr)[1]
66 except AttributeError:
67 pass
68 if not m:
69 #something weird here.. punt -ddm
70 return addr
71 else:
72 return "<%s>" % m
Guido van Rossum69a79bc1998-07-13 15:18:49 +000073
74def quotedata(data):
75 """Quote data for email.
76
Guido van Rossumfcfb6321998-08-04 15:29:54 +000077 Double leading '.', and change Unix newline '\n', or Mac '\r' into
Barry Warsawa7d9bdf1998-12-22 03:24:27 +000078 Internet CRLF end-of-line.
79 """
Guido van Rossum69a79bc1998-07-13 15:18:49 +000080 return re.sub(r'(?m)^\.', '..',
Guido van Rossumfcfb6321998-08-04 15:29:54 +000081 re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
Guido van Rossum69a79bc1998-07-13 15:18:49 +000082
Guido van Rossumbbe323e1998-01-29 17:24:40 +000083class SMTP:
Guido van Rossumfcfb6321998-08-04 15:29:54 +000084 """This class manages a connection to an SMTP or ESMTP server.
85 SMTP Objects:
86 SMTP objects have the following attributes:
87 helo_resp
88 This is the message given by the server in responce to the
89 most recent HELO command.
90
91 ehlo_resp
92 This is the message given by the server in responce to the
93 most recent EHLO command. This is usually multiline.
94
95 does_esmtp
96 This is a True value _after you do an EHLO command_, if the
97 server supports ESMTP.
98
99 esmtp_features
100 This is a dictionary, which, if the server supports ESMTP,
101 will _after you do an EHLO command_, contain the names of the
102 SMTP service extentions this server supports, and their
103 parameters (if any).
104 Note, all extention names are mapped to lower case in the
105 dictionary.
106
107 For method docs, see each method's docstrings. In general, there is
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000108 a method of the same name to perform each SMTP command, and there
109 is a method called 'sendmail' that will do an entire mail
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000110 transaction.
111 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000112 debuglevel = 0
113 file = None
114 helo_resp = None
115 ehlo_resp = None
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000116 does_esmtp = 0
Guido van Rossum95e6f701998-06-25 02:15:50 +0000117
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000118 def __init__(self, host = '', port = 0):
119 """Initialize a new instance.
120
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000121 If specified, `host' is the name of the remote host to which to
122 connect. If specified, `port' specifies the port to which to connect.
123 By default, smtplib.SMTP_PORT is used.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000124
125 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000126 self.esmtp_features = {}
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000127 if host: self.connect(host, port)
128
129 def set_debuglevel(self, debuglevel):
130 """Set the debug output level.
131
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000132 A non-false value results in debug messages for connection and for all
133 messages sent to and received from the server.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000134
135 """
136 self.debuglevel = debuglevel
137
138 def connect(self, host='localhost', port = 0):
139 """Connect to a host on a given port.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000140
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000141 If the hostname ends with a colon (`:') followed by a number, and
142 there is no port specified, that suffix will be stripped off and the
143 number interpreted as the port number to use.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000144
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000145 Note: This method is automatically invoked by __init__, if a host is
146 specified during instantiation.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000147
148 """
149 if not port:
150 i = string.find(host, ':')
151 if i >= 0:
152 host, port = host[:i], host[i+1:]
153 try: port = string.atoi(port)
154 except string.atoi_error:
155 raise socket.error, "nonnumeric port"
156 if not port: port = SMTP_PORT
157 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
158 if self.debuglevel > 0: print 'connect:', (host, port)
159 self.sock.connect(host, port)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 (code,msg)=self.getreply()
161 if self.debuglevel >0 : print "connect:", msg
162 return msg
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000163
164 def send(self, str):
165 """Send `str' to the server."""
166 if self.debuglevel > 0: print 'send:', `str`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 if self.sock:
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000168 try:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000169 self.sock.send(str)
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000170 except socket.error:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000171 raise SMTPServerDisconnected('Server not connected')
Guido van Rossumfc40a831998-01-29 17:26:45 +0000172 else:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000173 raise SMTPServerDisconnected('please run connect() first')
Guido van Rossumfc40a831998-01-29 17:26:45 +0000174
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000175 def putcmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000176 """Send a command to the server."""
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000177 str = '%s %s%s' % (cmd, args, CRLF)
178 self.send(str)
179
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000180 def getreply(self):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000181 """Get a reply from the server.
182
183 Returns a tuple consisting of:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000184
185 - server response code (e.g. '250', or such, if all goes well)
186 Note: returns -1 if it can't read response code.
187
188 - server response string corresponding to response code (multiline
189 responses are converted to a single, multiline string).
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000190 """
191 resp=[]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 self.file = self.sock.makefile('rb')
193 while 1:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000194 line = self.file.readline()
195 if self.debuglevel > 0: print 'reply:', `line`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 resp.append(string.strip(line[4:]))
197 code=line[:3]
198 #check if multiline resp
199 if line[3:4]!="-":
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000200 break
201 try:
202 errcode = string.atoi(code)
203 except(ValueError):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 errcode = -1
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000205
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 errmsg = string.join(resp,"\n")
207 if self.debuglevel > 0:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000208 print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000209 return errcode, errmsg
210
211 def docmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000212 """Send a command, and return its response code."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 self.putcmd(cmd,args)
214 (code,msg)=self.getreply()
215 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000216
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000217 # std smtp commands
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000218 def helo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000219 """SMTP 'helo' command.
220 Hostname to send for this command defaults to the FQDN of the local
221 host.
222 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 name=string.strip(name)
224 if len(name)==0:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000225 name=socket.gethostbyaddr(socket.gethostname())[0]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 self.putcmd("helo",name)
227 (code,msg)=self.getreply()
228 self.helo_resp=msg
229 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000230
Guido van Rossum95e6f701998-06-25 02:15:50 +0000231 def ehlo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000232 """ SMTP 'ehlo' command.
233 Hostname to send for this command defaults to the FQDN of the local
234 host.
235 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000236 name=string.strip(name)
237 if len(name)==0:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000238 name=socket.gethostbyaddr(socket.gethostname())[0]
Guido van Rossum95e6f701998-06-25 02:15:50 +0000239 self.putcmd("ehlo",name)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000240 (code,msg)=self.getreply()
241 # According to RFC1869 some (badly written)
242 # MTA's will disconnect on an ehlo. Toss an exception if
243 # that happens -ddm
244 if code == -1 and len(msg) == 0:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000245 raise SMTPServerDisconnected("Server not connected")
Guido van Rossum95e6f701998-06-25 02:15:50 +0000246 self.ehlo_resp=msg
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000247 if code<>250:
248 return code
249 self.does_esmtp=1
250 #parse the ehlo responce -ddm
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000251 resp=string.split(self.ehlo_resp,'\n')
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000252 del resp[0]
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000253 for each in resp:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000254 m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
255 if m:
256 feature=string.lower(m.group("feature"))
257 params=string.strip(m.string[m.end("feature"):])
258 self.esmtp_features[feature]=params
Guido van Rossum95e6f701998-06-25 02:15:50 +0000259 return code
260
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000261 def has_extn(self, opt):
262 """Does the server support a given SMTP service extension?"""
263 return self.esmtp_features.has_key(string.lower(opt))
Guido van Rossum95e6f701998-06-25 02:15:50 +0000264
Guido van Rossum18586f41998-04-03 17:03:13 +0000265 def help(self, args=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000266 """SMTP 'help' command.
267 Returns help text from server."""
Guido van Rossum18586f41998-04-03 17:03:13 +0000268 self.putcmd("help", args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 (code,msg)=self.getreply()
270 return msg
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000271
272 def rset(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000273 """SMTP 'rset' command -- resets session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000274 code=self.docmd("rset")
275 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000276
277 def noop(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000278 """SMTP 'noop' command -- doesn't do anything :>"""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 code=self.docmd("noop")
280 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000281
Guido van Rossum95e6f701998-06-25 02:15:50 +0000282 def mail(self,sender,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000283 """SMTP 'mail' command -- begins mail xfer session."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000284 optionlist = ''
285 if options and self.does_esmtp:
286 optionlist = string.join(options, ' ')
287 self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000289
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000290 def rcpt(self,recip,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000291 """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000292 optionlist = ''
293 if options and self.does_esmtp:
Guido van Rossum348fd061999-01-14 04:18:46 +0000294 optionlist = ' ' + string.join(options, ' ')
295 self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000296 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000297
298 def data(self,msg):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000299 """SMTP 'DATA' command -- sends message data to server.
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000300 Automatically quotes lines beginning with a period per rfc821.
301 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000302 self.putcmd("data")
303 (code,repl)=self.getreply()
304 if self.debuglevel >0 : print "data:", (code,repl)
305 if code <> 354:
306 return -1
307 else:
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000308 self.send(quotedata(msg))
309 self.send("%s.%s" % (CRLF, CRLF))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000310 (code,msg)=self.getreply()
311 if self.debuglevel >0 : print "data:", (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000312 return code
313
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000314 def verify(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000315 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000316 self.putcmd("vrfy", quoteaddr(address))
317 return self.getreply()
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000318 # a.k.a.
319 vrfy=verify
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000320
321 def expn(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000322 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000323 self.putcmd("expn", quoteaddr(address))
324 return self.getreply()
325
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000326 # some useful methods
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000327 def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
328 rcpt_options=[]):
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000329 """This command performs an entire mail transaction.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000330
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000331 The arguments are:
332 - from_addr : The address sending this mail.
333 - to_addrs : A list of addresses to send this mail to. A bare
334 string will be treated as a list with 1 address.
335 - msg : The message to send.
336 - mail_options : List of ESMTP options (such as 8bitmime) for the
337 mail command.
338 - rcpt_options : List of ESMTP options (such as DSN commands) for
339 all the rcpt commands.
340
341 If there has been no previous EHLO or HELO command this session, this
342 method tries ESMTP EHLO first. If the server does ESMTP, message size
343 and each of the specified options will be passed to it. If EHLO
344 fails, HELO will be tried and ESMTP options suppressed.
345
346 This method will return normally if the mail is accepted for at least
347 one recipient. Otherwise it will throw an exception (either
348 SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is,
349 if this method does not throw an exception, then someone should get
350 your mail. If this method does not throw an exception, it returns a
351 dictionary, with one entry for each recipient that was refused.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000352
Guido van Rossum95e6f701998-06-25 02:15:50 +0000353 Example:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000354
355 >>> import smtplib
356 >>> s=smtplib.SMTP("localhost")
Guido van Rossumfc40a831998-01-29 17:26:45 +0000357 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000358 >>> msg = '''
359 ... From: Me@my.org
360 ... Subject: testin'...
361 ...
362 ... This is a test '''
363 >>> s.sendmail("me@my.org",tolist,msg)
364 { "three@three.org" : ( 550 ,"User unknown" ) }
365 >>> s.quit()
366
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000367 In the above example, the message was accepted for delivery to three
368 of the four addresses, and one was rejected, with the error code
369 550. If all addresses are accepted, then the method will return an
370 empty dictionary.
371
372 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000373 if not self.helo_resp and not self.ehlo_resp:
374 if self.ehlo() >= 400:
375 self.helo()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000376 esmtp_opts = []
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000377 if self.does_esmtp:
378 # Hmmm? what's this? -ddm
379 # self.esmtp_features['7bit']=""
380 if self.has_extn('size'):
381 esmtp_opts.append("size=" + `len(msg)`)
382 for option in mail_options:
Guido van Rossum95e6f701998-06-25 02:15:50 +0000383 esmtp_opts.append(option)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000384
Guido van Rossum95e6f701998-06-25 02:15:50 +0000385 (code,resp) = self.mail(from_addr, esmtp_opts)
386 if code <> 250:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000388 raise SMTPSenderRefused('%s: %s' % (from_addr, resp))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 senderrs={}
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000390 if type(to_addrs) == types.StringType:
391 to_addrs = [to_addrs]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000392 for each in to_addrs:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000393 (code,resp)=self.rcpt(each, rcpt_options)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 if (code <> 250) and (code <> 251):
Guido van Rossumfc40a831998-01-29 17:26:45 +0000395 senderrs[each]=(code,resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000396 if len(senderrs)==len(to_addrs):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000397 # the server refused all our recipients
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000398 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000399 raise SMTPRecipientsRefused(string.join(
400 map(lambda x:"%s: %s" % (x[0], x[1][1]), senderrs.items()),
401 '; '))
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000402 code=self.data(msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000403 if code <>250 :
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000404 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000405 raise SMTPDataError('data transmission error: %s' % code)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000406 #if we got here then somebody got our mail
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000407 return senderrs
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000408
409
410 def close(self):
411 """Close the connection to the SMTP server."""
412 if self.file:
413 self.file.close()
414 self.file = None
415 if self.sock:
416 self.sock.close()
417 self.sock = None
418
419
420 def quit(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000421 """Terminate the SMTP session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 self.docmd("quit")
423 self.close()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000424
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000425
Guido van Rossum95e6f701998-06-25 02:15:50 +0000426# Test the sendmail method, which tests most of the others.
427# Note: This always sends to localhost.
428if __name__ == '__main__':
429 import sys, rfc822
430
431 def prompt(prompt):
432 sys.stdout.write(prompt + ": ")
433 return string.strip(sys.stdin.readline())
434
435 fromaddr = prompt("From")
436 toaddrs = string.splitfields(prompt("To"), ',')
437 print "Enter message, end with ^D:"
438 msg = ''
439 while 1:
440 line = sys.stdin.readline()
441 if not line:
442 break
443 msg = msg + line
444 print "Message length is " + `len(msg)`
445
446 server = SMTP('localhost')
447 server.set_debuglevel(1)
448 server.sendmail(fromaddr, toaddrs, msg)
449 server.quit()