blob: bd221dc4e936415996362b22c150dae9461f0cd9 [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 Rossumf123f841999-03-29 20:33:21 +0000190
191 Raises SMTPServerDisconnected if end-of-file is reached.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000192 """
193 resp=[]
Guido van Rossumf123f841999-03-29 20:33:21 +0000194 if self.file is None:
195 self.file = self.sock.makefile('rb')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 while 1:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000197 line = self.file.readline()
Guido van Rossumf123f841999-03-29 20:33:21 +0000198 if line == '':
199 self.close()
200 raise SMTPServerDisconnected("Connection unexpectedly closed")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000201 if self.debuglevel > 0: print 'reply:', `line`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 resp.append(string.strip(line[4:]))
203 code=line[:3]
Guido van Rossumf123f841999-03-29 20:33:21 +0000204 # Check that the error code is syntactically correct.
205 # Don't attempt to read a continuation line if it is broken.
206 try:
207 errcode = string.atoi(code)
208 except ValueError:
209 errcode = -1
210 break
211 # Check if multiline response.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 if line[3:4]!="-":
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000213 break
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000214
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 errmsg = string.join(resp,"\n")
216 if self.debuglevel > 0:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000217 print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000218 return errcode, errmsg
219
220 def docmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000221 """Send a command, and return its response code."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000222 self.putcmd(cmd,args)
223 (code,msg)=self.getreply()
224 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000225
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000226 # std smtp commands
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000227 def helo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000228 """SMTP 'helo' command.
229 Hostname to send for this command defaults to the FQDN of the local
230 host.
231 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000232 name=string.strip(name)
233 if len(name)==0:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000234 name=socket.gethostbyaddr(socket.gethostname())[0]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 self.putcmd("helo",name)
236 (code,msg)=self.getreply()
237 self.helo_resp=msg
238 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000239
Guido van Rossum95e6f701998-06-25 02:15:50 +0000240 def ehlo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000241 """ SMTP 'ehlo' command.
242 Hostname to send for this command defaults to the FQDN of the local
243 host.
244 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000245 name=string.strip(name)
246 if len(name)==0:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000247 name=socket.gethostbyaddr(socket.gethostname())[0]
Guido van Rossum95e6f701998-06-25 02:15:50 +0000248 self.putcmd("ehlo",name)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000249 (code,msg)=self.getreply()
250 # According to RFC1869 some (badly written)
251 # MTA's will disconnect on an ehlo. Toss an exception if
252 # that happens -ddm
253 if code == -1 and len(msg) == 0:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000254 raise SMTPServerDisconnected("Server not connected")
Guido van Rossum95e6f701998-06-25 02:15:50 +0000255 self.ehlo_resp=msg
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000256 if code<>250:
257 return code
258 self.does_esmtp=1
259 #parse the ehlo responce -ddm
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000260 resp=string.split(self.ehlo_resp,'\n')
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000261 del resp[0]
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000262 for each in resp:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000263 m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
264 if m:
265 feature=string.lower(m.group("feature"))
266 params=string.strip(m.string[m.end("feature"):])
267 self.esmtp_features[feature]=params
Guido van Rossum95e6f701998-06-25 02:15:50 +0000268 return code
269
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000270 def has_extn(self, opt):
271 """Does the server support a given SMTP service extension?"""
272 return self.esmtp_features.has_key(string.lower(opt))
Guido van Rossum95e6f701998-06-25 02:15:50 +0000273
Guido van Rossum18586f41998-04-03 17:03:13 +0000274 def help(self, args=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000275 """SMTP 'help' command.
276 Returns help text from server."""
Guido van Rossum18586f41998-04-03 17:03:13 +0000277 self.putcmd("help", args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000278 (code,msg)=self.getreply()
279 return msg
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000280
281 def rset(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000282 """SMTP 'rset' command -- resets session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 code=self.docmd("rset")
284 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000285
286 def noop(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000287 """SMTP 'noop' command -- doesn't do anything :>"""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 code=self.docmd("noop")
289 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000290
Guido van Rossum95e6f701998-06-25 02:15:50 +0000291 def mail(self,sender,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000292 """SMTP 'mail' command -- begins mail xfer session."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000293 optionlist = ''
294 if options and self.does_esmtp:
295 optionlist = string.join(options, ' ')
296 self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000297 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000298
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000299 def rcpt(self,recip,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000300 """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000301 optionlist = ''
302 if options and self.does_esmtp:
Guido van Rossum348fd061999-01-14 04:18:46 +0000303 optionlist = ' ' + string.join(options, ' ')
304 self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000305 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000306
307 def data(self,msg):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000308 """SMTP 'DATA' command -- sends message data to server.
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000309 Automatically quotes lines beginning with a period per rfc821.
310 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000311 self.putcmd("data")
312 (code,repl)=self.getreply()
313 if self.debuglevel >0 : print "data:", (code,repl)
314 if code <> 354:
315 return -1
316 else:
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000317 self.send(quotedata(msg))
318 self.send("%s.%s" % (CRLF, CRLF))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000319 (code,msg)=self.getreply()
320 if self.debuglevel >0 : print "data:", (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000321 return code
322
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000323 def verify(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000324 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000325 self.putcmd("vrfy", quoteaddr(address))
326 return self.getreply()
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000327 # a.k.a.
328 vrfy=verify
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000329
330 def expn(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000331 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000332 self.putcmd("expn", quoteaddr(address))
333 return self.getreply()
334
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000335 # some useful methods
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000336 def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
337 rcpt_options=[]):
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000338 """This command performs an entire mail transaction.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000339
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000340 The arguments are:
341 - from_addr : The address sending this mail.
342 - to_addrs : A list of addresses to send this mail to. A bare
343 string will be treated as a list with 1 address.
344 - msg : The message to send.
345 - mail_options : List of ESMTP options (such as 8bitmime) for the
346 mail command.
347 - rcpt_options : List of ESMTP options (such as DSN commands) for
348 all the rcpt commands.
349
350 If there has been no previous EHLO or HELO command this session, this
351 method tries ESMTP EHLO first. If the server does ESMTP, message size
352 and each of the specified options will be passed to it. If EHLO
353 fails, HELO will be tried and ESMTP options suppressed.
354
355 This method will return normally if the mail is accepted for at least
356 one recipient. Otherwise it will throw an exception (either
357 SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError) That is,
358 if this method does not throw an exception, then someone should get
359 your mail. If this method does not throw an exception, it returns a
360 dictionary, with one entry for each recipient that was refused.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000361
Guido van Rossum95e6f701998-06-25 02:15:50 +0000362 Example:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000363
364 >>> import smtplib
365 >>> s=smtplib.SMTP("localhost")
Guido van Rossumfc40a831998-01-29 17:26:45 +0000366 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000367 >>> msg = '''
368 ... From: Me@my.org
369 ... Subject: testin'...
370 ...
371 ... This is a test '''
372 >>> s.sendmail("me@my.org",tolist,msg)
373 { "three@three.org" : ( 550 ,"User unknown" ) }
374 >>> s.quit()
375
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000376 In the above example, the message was accepted for delivery to three
377 of the four addresses, and one was rejected, with the error code
378 550. If all addresses are accepted, then the method will return an
379 empty dictionary.
380
381 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000382 if not self.helo_resp and not self.ehlo_resp:
383 if self.ehlo() >= 400:
384 self.helo()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000385 esmtp_opts = []
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000386 if self.does_esmtp:
387 # Hmmm? what's this? -ddm
388 # self.esmtp_features['7bit']=""
389 if self.has_extn('size'):
390 esmtp_opts.append("size=" + `len(msg)`)
391 for option in mail_options:
Guido van Rossum95e6f701998-06-25 02:15:50 +0000392 esmtp_opts.append(option)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000393
Guido van Rossum95e6f701998-06-25 02:15:50 +0000394 (code,resp) = self.mail(from_addr, esmtp_opts)
395 if code <> 250:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000397 raise SMTPSenderRefused('%s: %s' % (from_addr, resp))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000398 senderrs={}
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000399 if type(to_addrs) == types.StringType:
400 to_addrs = [to_addrs]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000401 for each in to_addrs:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000402 (code,resp)=self.rcpt(each, rcpt_options)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000403 if (code <> 250) and (code <> 251):
Guido van Rossumfc40a831998-01-29 17:26:45 +0000404 senderrs[each]=(code,resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000405 if len(senderrs)==len(to_addrs):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000406 # the server refused all our recipients
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000407 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000408 raise SMTPRecipientsRefused(string.join(
409 map(lambda x:"%s: %s" % (x[0], x[1][1]), senderrs.items()),
410 '; '))
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000411 code=self.data(msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 if code <>250 :
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000413 self.rset()
Guido van Rossum40233ea1999-01-15 03:23:55 +0000414 raise SMTPDataError('data transmission error: %s' % code)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000415 #if we got here then somebody got our mail
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000416 return senderrs
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000417
418
419 def close(self):
420 """Close the connection to the SMTP server."""
421 if self.file:
422 self.file.close()
423 self.file = None
424 if self.sock:
425 self.sock.close()
426 self.sock = None
427
428
429 def quit(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000430 """Terminate the SMTP session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 self.docmd("quit")
432 self.close()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000433
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000434
Guido van Rossum95e6f701998-06-25 02:15:50 +0000435# Test the sendmail method, which tests most of the others.
436# Note: This always sends to localhost.
437if __name__ == '__main__':
438 import sys, rfc822
439
440 def prompt(prompt):
441 sys.stdout.write(prompt + ": ")
442 return string.strip(sys.stdin.readline())
443
444 fromaddr = prompt("From")
445 toaddrs = string.splitfields(prompt("To"), ',')
446 print "Enter message, end with ^D:"
447 msg = ''
448 while 1:
449 line = sys.stdin.readline()
450 if not line:
451 break
452 msg = msg + line
453 print "Message length is " + `len(msg)`
454
455 server = SMTP('localhost')
456 server.set_debuglevel(1)
457 server.sendmail(fromaddr, toaddrs, msg)
458 server.quit()