blob: 1c42233f2627687612b09bec1f1e9fd036502b55 [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
Guido van Rossum296e1431999-04-07 15:03:39 +000051# Exception classes used by this module.
52class SMTPException(Exception):
53 """Base class for all exceptions raised by this module."""
54
55class SMTPServerDisconnected(SMTPException):
56 """Not connected to any SMTP server.
57
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.
61 """
62
63class SMTPResponseException(SMTPException):
64 """Base class for all exceptions that include an SMTP error code.
65
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.
70 """
71
72 def __init__(self, code, msg):
73 self.smtp_code = code
74 self.smtp_error = msg
75 self.args = (code, msg)
76
77class SMTPSenderRefused(SMTPResponseException):
78 """Sender address refused.
79 In addition to the attributes set by on all SMTPResponseException
Barry Warsawd25c1b71999-11-28 17:11:06 +000080 exceptions, this sets `sender' to the string that the SMTP refused.
Guido van Rossum296e1431999-04-07 15:03:39 +000081 """
82
83 def __init__(self, code, msg, sender):
84 self.smtp_code = code
85 self.smtp_error = msg
86 self.sender = sender
87 self.args = (code, msg, sender)
88
Guido van Rossum20c92281999-04-21 16:52:20 +000089class SMTPRecipientsRefused(SMTPException):
Barry Warsawd25c1b71999-11-28 17:11:06 +000090 """All recipient addresses refused.
Guido van Rossum296e1431999-04-07 15:03:39 +000091 The errors for each recipient are accessable thru the attribute
92 'recipients', which is a dictionary of exactly the same sort as
93 SMTP.sendmail() returns.
94 """
95
96 def __init__(self, recipients):
97 self.recipients = recipients
98 self.args = ( recipients,)
99
100
101
102class SMTPDataError(SMTPResponseException):
103 """The SMTP server didn't accept the data."""
104
105class SMTPConnectError(SMTPResponseException):
Barry Warsawd25c1b71999-11-28 17:11:06 +0000106 """Error during connection establishment."""
Guido van Rossum296e1431999-04-07 15:03:39 +0000107
108class SMTPHeloError(SMTPResponseException):
Barry Warsawd25c1b71999-11-28 17:11:06 +0000109 """The server refused our HELO reply."""
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000110
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000111def quoteaddr(addr):
112 """Quote a subset of the email addresses defined by RFC 821.
113
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000114 Should be able to handle anything rfc822.parseaddr can handle.
115 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000116 m=None
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000117 try:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000118 m=rfc822.parseaddr(addr)[1]
119 except AttributeError:
120 pass
121 if not m:
122 #something weird here.. punt -ddm
123 return addr
124 else:
125 return "<%s>" % m
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000126
127def quotedata(data):
128 """Quote data for email.
129
Barry Warsawd25c1b71999-11-28 17:11:06 +0000130 Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000131 Internet CRLF end-of-line.
132 """
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000133 return re.sub(r'(?m)^\.', '..',
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000134 re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000135
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000136class SMTP:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000137 """This class manages a connection to an SMTP or ESMTP server.
138 SMTP Objects:
139 SMTP objects have the following attributes:
140 helo_resp
Barry Warsawd25c1b71999-11-28 17:11:06 +0000141 This is the message given by the server in response to the
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000142 most recent HELO command.
143
144 ehlo_resp
Barry Warsawd25c1b71999-11-28 17:11:06 +0000145 This is the message given by the server in response to the
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000146 most recent EHLO command. This is usually multiline.
147
148 does_esmtp
149 This is a True value _after you do an EHLO command_, if the
150 server supports ESMTP.
151
152 esmtp_features
153 This is a dictionary, which, if the server supports ESMTP,
Barry Warsawd25c1b71999-11-28 17:11:06 +0000154 will _after you do an EHLO command_, contain the names of the
155 SMTP service extensions this server supports, and their
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000156 parameters (if any).
Barry Warsawd25c1b71999-11-28 17:11:06 +0000157
158 Note, all extension names are mapped to lower case in the
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000159 dictionary.
160
Barry Warsawd25c1b71999-11-28 17:11:06 +0000161 See each method's docstrings for details. In general, there is a
162 method of the same name to perform each SMTP command. There is also a
163 method called 'sendmail' that will do an entire mail transaction.
164 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000165 debuglevel = 0
166 file = None
167 helo_resp = None
168 ehlo_resp = None
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000169 does_esmtp = 0
Guido van Rossum95e6f701998-06-25 02:15:50 +0000170
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000171 def __init__(self, host = '', port = 0):
172 """Initialize a new instance.
173
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000174 If specified, `host' is the name of the remote host to which to
175 connect. If specified, `port' specifies the port to which to connect.
Barry Warsawd25c1b71999-11-28 17:11:06 +0000176 By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
177 if the specified `host' doesn't respond correctly.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000178
179 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000180 self.esmtp_features = {}
Guido van Rossum296e1431999-04-07 15:03:39 +0000181 if host:
182 (code, msg) = self.connect(host, port)
183 if code != 220:
184 raise SMTPConnectError(code, msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000185
186 def set_debuglevel(self, debuglevel):
187 """Set the debug output level.
188
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000189 A non-false value results in debug messages for connection and for all
190 messages sent to and received from the server.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000191
192 """
193 self.debuglevel = debuglevel
194
195 def connect(self, host='localhost', port = 0):
196 """Connect to a host on a given port.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000197
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000198 If the hostname ends with a colon (`:') followed by a number, and
199 there is no port specified, that suffix will be stripped off and the
200 number interpreted as the port number to use.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000201
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000202 Note: This method is automatically invoked by __init__, if a host is
203 specified during instantiation.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000204
205 """
206 if not port:
207 i = string.find(host, ':')
208 if i >= 0:
209 host, port = host[:i], host[i+1:]
210 try: port = string.atoi(port)
211 except string.atoi_error:
212 raise socket.error, "nonnumeric port"
213 if not port: port = SMTP_PORT
214 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
215 if self.debuglevel > 0: print 'connect:', (host, port)
216 self.sock.connect(host, port)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 (code,msg)=self.getreply()
218 if self.debuglevel >0 : print "connect:", msg
Guido van Rossum296e1431999-04-07 15:03:39 +0000219 return (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000220
221 def send(self, str):
222 """Send `str' to the server."""
223 if self.debuglevel > 0: print 'send:', `str`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 if self.sock:
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000225 try:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000226 self.sock.send(str)
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000227 except socket.error:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000228 raise SMTPServerDisconnected('Server not connected')
Guido van Rossumfc40a831998-01-29 17:26:45 +0000229 else:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000230 raise SMTPServerDisconnected('please run connect() first')
Guido van Rossumfc40a831998-01-29 17:26:45 +0000231
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000232 def putcmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000233 """Send a command to the server."""
Guido van Rossumdb23d3d1999-06-09 15:13:10 +0000234 if args == "":
235 str = '%s%s' % (cmd, CRLF)
236 else:
237 str = '%s %s%s' % (cmd, args, CRLF)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000238 self.send(str)
239
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000240 def getreply(self):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000241 """Get a reply from the server.
242
243 Returns a tuple consisting of:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000244
245 - server response code (e.g. '250', or such, if all goes well)
246 Note: returns -1 if it can't read response code.
247
248 - server response string corresponding to response code (multiline
249 responses are converted to a single, multiline string).
Guido van Rossumf123f841999-03-29 20:33:21 +0000250
251 Raises SMTPServerDisconnected if end-of-file is reached.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000252 """
253 resp=[]
Guido van Rossum296e1431999-04-07 15:03:39 +0000254 if self.file is None:
255 self.file = self.sock.makefile('rb')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 while 1:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000257 line = self.file.readline()
Guido van Rossum296e1431999-04-07 15:03:39 +0000258 if line == '':
259 self.close()
260 raise SMTPServerDisconnected("Connection unexpectedly closed")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000261 if self.debuglevel > 0: print 'reply:', `line`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000262 resp.append(string.strip(line[4:]))
263 code=line[:3]
Guido van Rossum296e1431999-04-07 15:03:39 +0000264 # Check that the error code is syntactically correct.
265 # Don't attempt to read a continuation line if it is broken.
266 try:
267 errcode = string.atoi(code)
268 except ValueError:
269 errcode = -1
270 break
Guido van Rossumf123f841999-03-29 20:33:21 +0000271 # Check if multiline response.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000272 if line[3:4]!="-":
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000273 break
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000274
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 errmsg = string.join(resp,"\n")
276 if self.debuglevel > 0:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000277 print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000278 return errcode, errmsg
279
280 def docmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000281 """Send a command, and return its response code."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000282 self.putcmd(cmd,args)
Guido van Rossum296e1431999-04-07 15:03:39 +0000283 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000284
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000285 # std smtp commands
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000286 def helo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000287 """SMTP 'helo' command.
288 Hostname to send for this command defaults to the FQDN of the local
289 host.
290 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 name=string.strip(name)
292 if len(name)==0:
Guido van Rossumbda10c81999-10-22 13:09:20 +0000293 name = socket.gethostname()
294 try:
295 name = socket.gethostbyaddr(name)[0]
296 except socket.error:
297 pass
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000298 self.putcmd("helo",name)
299 (code,msg)=self.getreply()
300 self.helo_resp=msg
Guido van Rossum296e1431999-04-07 15:03:39 +0000301 return (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000302
Guido van Rossum95e6f701998-06-25 02:15:50 +0000303 def ehlo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000304 """ SMTP 'ehlo' command.
305 Hostname to send for this command defaults to the FQDN of the local
306 host.
307 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000308 name=string.strip(name)
309 if len(name)==0:
Guido van Rossumbda10c81999-10-22 13:09:20 +0000310 name = socket.gethostname()
311 try:
312 name = socket.gethostbyaddr(name)[0]
313 except socket.error:
314 pass
Guido van Rossum95e6f701998-06-25 02:15:50 +0000315 self.putcmd("ehlo",name)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000316 (code,msg)=self.getreply()
317 # According to RFC1869 some (badly written)
318 # MTA's will disconnect on an ehlo. Toss an exception if
319 # that happens -ddm
320 if code == -1 and len(msg) == 0:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000321 raise SMTPServerDisconnected("Server not connected")
Guido van Rossum95e6f701998-06-25 02:15:50 +0000322 self.ehlo_resp=msg
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000323 if code<>250:
Guido van Rossum296e1431999-04-07 15:03:39 +0000324 return (code,msg)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000325 self.does_esmtp=1
326 #parse the ehlo responce -ddm
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000327 resp=string.split(self.ehlo_resp,'\n')
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000328 del resp[0]
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000329 for each in resp:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000330 m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
331 if m:
332 feature=string.lower(m.group("feature"))
333 params=string.strip(m.string[m.end("feature"):])
334 self.esmtp_features[feature]=params
Guido van Rossum296e1431999-04-07 15:03:39 +0000335 return (code,msg)
Guido van Rossum95e6f701998-06-25 02:15:50 +0000336
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000337 def has_extn(self, opt):
338 """Does the server support a given SMTP service extension?"""
339 return self.esmtp_features.has_key(string.lower(opt))
Guido van Rossum95e6f701998-06-25 02:15:50 +0000340
Guido van Rossum18586f41998-04-03 17:03:13 +0000341 def help(self, args=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000342 """SMTP 'help' command.
343 Returns help text from server."""
Guido van Rossum18586f41998-04-03 17:03:13 +0000344 self.putcmd("help", args)
Guido van Rossum296e1431999-04-07 15:03:39 +0000345 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000346
347 def rset(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000348 """SMTP 'rset' command -- resets session."""
Guido van Rossum296e1431999-04-07 15:03:39 +0000349 return self.docmd("rset")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000350
351 def noop(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000352 """SMTP 'noop' command -- doesn't do anything :>"""
Guido van Rossum296e1431999-04-07 15:03:39 +0000353 return self.docmd("noop")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000354
Guido van Rossum95e6f701998-06-25 02:15:50 +0000355 def mail(self,sender,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000356 """SMTP 'mail' command -- begins mail xfer session."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000357 optionlist = ''
358 if options and self.does_esmtp:
Guido van Rossumdb23d3d1999-06-09 15:13:10 +0000359 optionlist = ' ' + string.join(options, ' ')
360 self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000362
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000363 def rcpt(self,recip,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000364 """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000365 optionlist = ''
366 if options and self.does_esmtp:
Guido van Rossum348fd061999-01-14 04:18:46 +0000367 optionlist = ' ' + string.join(options, ' ')
368 self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000369 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000370
371 def data(self,msg):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000372 """SMTP 'DATA' command -- sends message data to server.
Guido van Rossum296e1431999-04-07 15:03:39 +0000373
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000374 Automatically quotes lines beginning with a period per rfc821.
Guido van Rossum296e1431999-04-07 15:03:39 +0000375 Raises SMTPDataError if there is an unexpected reply to the
376 DATA command; the return value from this method is the final
377 response code received when the all data is sent.
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000378 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 self.putcmd("data")
380 (code,repl)=self.getreply()
381 if self.debuglevel >0 : print "data:", (code,repl)
382 if code <> 354:
Guido van Rossum296e1431999-04-07 15:03:39 +0000383 raise SMTPDataError(code,repl)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000384 else:
Guido van Rossum20c92281999-04-21 16:52:20 +0000385 q = quotedata(msg)
386 if q[-2:] != CRLF:
387 q = q + CRLF
388 q = q + "." + CRLF
389 self.send(q)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000390 (code,msg)=self.getreply()
391 if self.debuglevel >0 : print "data:", (code,msg)
Guido van Rossum296e1431999-04-07 15:03:39 +0000392 return (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000393
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000394 def verify(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000395 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000396 self.putcmd("vrfy", quoteaddr(address))
397 return self.getreply()
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000398 # a.k.a.
399 vrfy=verify
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000400
401 def expn(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000402 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000403 self.putcmd("expn", quoteaddr(address))
404 return self.getreply()
405
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000406 # some useful methods
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000407 def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
408 rcpt_options=[]):
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000409 """This command performs an entire mail transaction.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000410
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000411 The arguments are:
412 - from_addr : The address sending this mail.
413 - to_addrs : A list of addresses to send this mail to. A bare
414 string will be treated as a list with 1 address.
415 - msg : The message to send.
416 - mail_options : List of ESMTP options (such as 8bitmime) for the
417 mail command.
418 - rcpt_options : List of ESMTP options (such as DSN commands) for
419 all the rcpt commands.
420
421 If there has been no previous EHLO or HELO command this session, this
422 method tries ESMTP EHLO first. If the server does ESMTP, message size
423 and each of the specified options will be passed to it. If EHLO
424 fails, HELO will be tried and ESMTP options suppressed.
425
426 This method will return normally if the mail is accepted for at least
Barry Warsawd25c1b71999-11-28 17:11:06 +0000427 one recipient. It returns a dictionary, with one entry for each
428 recipient that was refused. Each entry contains a tuple of the SMTP
429 error code and the accompanying error message sent by the server.
Guido van Rossum296e1431999-04-07 15:03:39 +0000430
431 This method may raise the following exceptions:
432
433 SMTPHeloError The server didn't reply properly to
434 the helo greeting.
Barry Warsawd25c1b71999-11-28 17:11:06 +0000435 SMTPRecipientsRefused The server rejected ALL recipients
Guido van Rossum296e1431999-04-07 15:03:39 +0000436 (no mail was sent).
437 SMTPSenderRefused The server didn't accept the from_addr.
438 SMTPDataError The server replied with an unexpected
439 error code (other than a refusal of
440 a recipient).
441
442 Note: the connection will be open even after an exception is raised.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000443
Guido van Rossum95e6f701998-06-25 02:15:50 +0000444 Example:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000445
446 >>> import smtplib
447 >>> s=smtplib.SMTP("localhost")
Guido van Rossumfc40a831998-01-29 17:26:45 +0000448 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000449 >>> msg = '''
450 ... From: Me@my.org
451 ... Subject: testin'...
452 ...
453 ... This is a test '''
454 >>> s.sendmail("me@my.org",tolist,msg)
455 { "three@three.org" : ( 550 ,"User unknown" ) }
456 >>> s.quit()
457
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000458 In the above example, the message was accepted for delivery to three
459 of the four addresses, and one was rejected, with the error code
Barry Warsawd25c1b71999-11-28 17:11:06 +0000460 550. If all addresses are accepted, then the method will return an
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000461 empty dictionary.
462
463 """
Guido van Rossum296e1431999-04-07 15:03:39 +0000464 if self.helo_resp is None and self.ehlo_resp is None:
465 if not (200 <= self.ehlo()[0] <= 299):
466 (code,resp) = self.helo()
467 if not (200 <= code <= 299):
468 raise SMTPHeloError(code, resp)
Guido van Rossum95e6f701998-06-25 02:15:50 +0000469 esmtp_opts = []
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000470 if self.does_esmtp:
471 # Hmmm? what's this? -ddm
472 # self.esmtp_features['7bit']=""
473 if self.has_extn('size'):
474 esmtp_opts.append("size=" + `len(msg)`)
475 for option in mail_options:
Guido van Rossum95e6f701998-06-25 02:15:50 +0000476 esmtp_opts.append(option)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000477
Guido van Rossum95e6f701998-06-25 02:15:50 +0000478 (code,resp) = self.mail(from_addr, esmtp_opts)
479 if code <> 250:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000480 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000481 raise SMTPSenderRefused(code, resp, from_addr)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000482 senderrs={}
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000483 if type(to_addrs) == types.StringType:
484 to_addrs = [to_addrs]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000485 for each in to_addrs:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000486 (code,resp)=self.rcpt(each, rcpt_options)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 if (code <> 250) and (code <> 251):
Guido van Rossumfc40a831998-01-29 17:26:45 +0000488 senderrs[each]=(code,resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000489 if len(senderrs)==len(to_addrs):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000490 # the server refused all our recipients
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000491 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000492 raise SMTPRecipientsRefused(senderrs)
493 (code,resp)=self.data(msg)
494 if code <> 250:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000495 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000496 raise SMTPDataError(code, resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000497 #if we got here then somebody got our mail
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000498 return senderrs
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000499
500
501 def close(self):
502 """Close the connection to the SMTP server."""
503 if self.file:
504 self.file.close()
505 self.file = None
506 if self.sock:
507 self.sock.close()
508 self.sock = None
509
510
511 def quit(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000512 """Terminate the SMTP session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000513 self.docmd("quit")
514 self.close()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000515
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000516
Guido van Rossum95e6f701998-06-25 02:15:50 +0000517# Test the sendmail method, which tests most of the others.
518# Note: This always sends to localhost.
519if __name__ == '__main__':
520 import sys, rfc822
521
522 def prompt(prompt):
523 sys.stdout.write(prompt + ": ")
524 return string.strip(sys.stdin.readline())
525
526 fromaddr = prompt("From")
527 toaddrs = string.splitfields(prompt("To"), ',')
528 print "Enter message, end with ^D:"
529 msg = ''
530 while 1:
531 line = sys.stdin.readline()
532 if not line:
533 break
534 msg = msg + line
535 print "Message length is " + `len(msg)`
536
537 server = SMTP('localhost')
538 server.set_debuglevel(1)
539 server.sendmail(fromaddr, toaddrs, msg)
540 server.quit()