blob: 3d28b0d56682ffa4d10595a4e0d5a75398d696fb [file] [log] [blame]
Barry Warsaw4c4bec81998-12-22 03:02:20 +00001#! /usr/bin/env python
2
Barry Warsawa1ae8842000-07-09 21:24:31 +00003'''SMTP/ESMTP client class.
Guido van Rossumbbe323e1998-01-29 17:24:40 +00004
Guido van Rossum95e6f701998-06-25 02:15:50 +00005This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
Guido van Rossumbbe323e1998-01-29 17:24:40 +00006
Guido van Rossumfcfb6321998-08-04 15:29:54 +00007Notes:
8
9Please remember, when doing ESMTP, that the names of the SMTP service
Barry Warsaw4c4bec81998-12-22 03:02:20 +000010extensions are NOT the same thing as the option keywords for the RCPT
Guido van Rossumfcfb6321998-08-04 15:29:54 +000011and MAIL commands!
12
Guido van Rossumbbe323e1998-01-29 17:24:40 +000013Example:
14
Barry Warsawa7d9bdf1998-12-22 03:24:27 +000015 >>> import smtplib
16 >>> s=smtplib.SMTP("localhost")
17 >>> print s.help()
18 This is Sendmail version 8.8.4
19 Topics:
20 HELO EHLO MAIL RCPT DATA
21 RSET NOOP QUIT HELP VRFY
22 EXPN VERB ETRN DSN
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.
27 End of HELP info
28 >>> s.putcmd("vrfy","someone@here")
29 >>> s.getreply()
30 (250, "Somebody OverHere <somebody@here.my.org>")
31 >>> s.quit()
Barry Warsawa1ae8842000-07-09 21:24:31 +000032'''
Guido van Rossumbbe323e1998-01-29 17:24:40 +000033
Guido van Rossum98d9fd32000-02-28 15:12:25 +000034# 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.
Tim Peters495ad3c2001-01-15 01:36:40 +000039#
Guido van Rossum98d9fd32000-02-28 15:12:25 +000040# This was modified from the Python 1.5 library HTTP lib.
41
Guido van Rossumbbe323e1998-01-29 17:24:40 +000042import socket
Barry Warsaw07201771998-12-22 20:37:36 +000043import re
Guido van Rossumfcfb6321998-08-04 15:29:54 +000044import rfc822
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +000045import types
Guido van Rossumbbe323e1998-01-29 17:24:40 +000046
Skip Montanaro0de65802001-02-15 22:15:14 +000047__all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException",
48 "SMTPSenderRefused","SMTPRecipientsRefused","SMTPDataError",
49 "SMTPConnectError","SMTPHeloError","quoteaddr","quotedata",
50 "SMTP"]
51
Guido van Rossumbbe323e1998-01-29 17:24:40 +000052SMTP_PORT = 25
53CRLF="\r\n"
54
Tim Peters495ad3c2001-01-15 01:36:40 +000055# Exception classes used by this module.
Guido van Rossum296e1431999-04-07 15:03:39 +000056class SMTPException(Exception):
57 """Base class for all exceptions raised by this module."""
58
59class SMTPServerDisconnected(SMTPException):
60 """Not connected to any SMTP server.
61
62 This exception is raised when the server unexpectedly disconnects,
63 or when an attempt is made to use the SMTP instance before
64 connecting it to a server.
65 """
66
67class SMTPResponseException(SMTPException):
68 """Base class for all exceptions that include an SMTP error code.
69
70 These exceptions are generated in some instances when the SMTP
71 server returns an error code. The error code is stored in the
72 `smtp_code' attribute of the error, and the `smtp_error' attribute
73 is set to the error message.
74 """
75
76 def __init__(self, code, msg):
77 self.smtp_code = code
78 self.smtp_error = msg
79 self.args = (code, msg)
80
81class SMTPSenderRefused(SMTPResponseException):
82 """Sender address refused.
83 In addition to the attributes set by on all SMTPResponseException
Barry Warsawd25c1b71999-11-28 17:11:06 +000084 exceptions, this sets `sender' to the string that the SMTP refused.
Guido van Rossum296e1431999-04-07 15:03:39 +000085 """
86
87 def __init__(self, code, msg, sender):
88 self.smtp_code = code
89 self.smtp_error = msg
90 self.sender = sender
91 self.args = (code, msg, sender)
92
Guido van Rossum20c92281999-04-21 16:52:20 +000093class SMTPRecipientsRefused(SMTPException):
Barry Warsawd25c1b71999-11-28 17:11:06 +000094 """All recipient addresses refused.
Thomas Wouters7e474022000-07-16 12:04:32 +000095 The errors for each recipient are accessible through the attribute
Tim Peters495ad3c2001-01-15 01:36:40 +000096 'recipients', which is a dictionary of exactly the same sort as
97 SMTP.sendmail() returns.
Guido van Rossum296e1431999-04-07 15:03:39 +000098 """
99
100 def __init__(self, recipients):
101 self.recipients = recipients
102 self.args = ( recipients,)
103
104
Guido van Rossum296e1431999-04-07 15:03:39 +0000105class SMTPDataError(SMTPResponseException):
106 """The SMTP server didn't accept the data."""
107
108class SMTPConnectError(SMTPResponseException):
Barry Warsawd25c1b71999-11-28 17:11:06 +0000109 """Error during connection establishment."""
Guido van Rossum296e1431999-04-07 15:03:39 +0000110
111class SMTPHeloError(SMTPResponseException):
Barry Warsawd25c1b71999-11-28 17:11:06 +0000112 """The server refused our HELO reply."""
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000113
Peter Schneider-Kamp7bc82bb2000-08-10 14:02:23 +0000114
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000115def quoteaddr(addr):
116 """Quote a subset of the email addresses defined by RFC 821.
117
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000118 Should be able to handle anything rfc822.parseaddr can handle.
119 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000120 m=None
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000121 try:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000122 m=rfc822.parseaddr(addr)[1]
123 except AttributeError:
124 pass
125 if not m:
126 #something weird here.. punt -ddm
127 return addr
128 else:
129 return "<%s>" % m
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000130
131def quotedata(data):
132 """Quote data for email.
133
Barry Warsawd25c1b71999-11-28 17:11:06 +0000134 Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000135 Internet CRLF end-of-line.
136 """
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000137 return re.sub(r'(?m)^\.', '..',
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000138 re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
Guido van Rossum69a79bc1998-07-13 15:18:49 +0000139
Peter Schneider-Kamp7bc82bb2000-08-10 14:02:23 +0000140
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000141class SMTP:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000142 """This class manages a connection to an SMTP or ESMTP server.
143 SMTP Objects:
Tim Peters495ad3c2001-01-15 01:36:40 +0000144 SMTP objects have the following attributes:
145 helo_resp
146 This is the message given by the server in response to the
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000147 most recent HELO command.
Tim Peters495ad3c2001-01-15 01:36:40 +0000148
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000149 ehlo_resp
Tim Peters495ad3c2001-01-15 01:36:40 +0000150 This is the message given by the server in response to the
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000151 most recent EHLO command. This is usually multiline.
152
Tim Peters495ad3c2001-01-15 01:36:40 +0000153 does_esmtp
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000154 This is a True value _after you do an EHLO command_, if the
155 server supports ESMTP.
156
Tim Peters495ad3c2001-01-15 01:36:40 +0000157 esmtp_features
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000158 This is a dictionary, which, if the server supports ESMTP,
Barry Warsawd25c1b71999-11-28 17:11:06 +0000159 will _after you do an EHLO command_, contain the names of the
160 SMTP service extensions this server supports, and their
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000161 parameters (if any).
Barry Warsawd25c1b71999-11-28 17:11:06 +0000162
Tim Peters495ad3c2001-01-15 01:36:40 +0000163 Note, all extension names are mapped to lower case in the
164 dictionary.
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000165
Barry Warsawd25c1b71999-11-28 17:11:06 +0000166 See each method's docstrings for details. In general, there is a
167 method of the same name to perform each SMTP command. There is also a
168 method called 'sendmail' that will do an entire mail transaction.
169 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000170 debuglevel = 0
171 file = None
172 helo_resp = None
173 ehlo_resp = None
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000174 does_esmtp = 0
Guido van Rossum95e6f701998-06-25 02:15:50 +0000175
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000176 def __init__(self, host = '', port = 0):
177 """Initialize a new instance.
178
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000179 If specified, `host' is the name of the remote host to which to
180 connect. If specified, `port' specifies the port to which to connect.
Barry Warsawd25c1b71999-11-28 17:11:06 +0000181 By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
182 if the specified `host' doesn't respond correctly.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000183
184 """
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000185 self.esmtp_features = {}
Guido van Rossum296e1431999-04-07 15:03:39 +0000186 if host:
187 (code, msg) = self.connect(host, port)
188 if code != 220:
189 raise SMTPConnectError(code, msg)
Tim Peters495ad3c2001-01-15 01:36:40 +0000190
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000191 def set_debuglevel(self, debuglevel):
192 """Set the debug output level.
193
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000194 A non-false value results in debug messages for connection and for all
195 messages sent to and received from the server.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000196
197 """
198 self.debuglevel = debuglevel
199
200 def connect(self, host='localhost', port = 0):
201 """Connect to a host on a given port.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000202
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000203 If the hostname ends with a colon (`:') followed by a number, and
204 there is no port specified, that suffix will be stripped off and the
205 number interpreted as the port number to use.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000206
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000207 Note: This method is automatically invoked by __init__, if a host is
208 specified during instantiation.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000209
210 """
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000211 if not port and (host.find(':') == host.rfind(':')):
Martin v. Löwisa43c2f82001-07-24 20:34:08 +0000212 i = host.rfind(':')
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000213 if i >= 0:
214 host, port = host[:i], host[i+1:]
Eric S. Raymondc013f302001-02-09 05:40:38 +0000215 try: port = int(port)
Eric S. Raymond8d876032001-02-09 10:14:53 +0000216 except ValueError:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000217 raise socket.error, "nonnumeric port"
218 if not port: port = SMTP_PORT
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000219 if self.debuglevel > 0: print 'connect:', (host, port)
Martin v. Löwis2ad25692001-07-31 08:40:21 +0000220 msg = "getaddrinfo returns an empty list"
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000221 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
222 af, socktype, proto, canonname, sa = res
223 try:
224 self.sock = socket.socket(af, socktype, proto)
225 if self.debuglevel > 0: print 'connect:', (host, port)
226 self.sock.connect(sa)
227 except socket.error, msg:
228 if self.debuglevel > 0: print 'connect fail:', (host, port)
229 self.sock.close()
230 self.sock = None
231 continue
232 break
233 if not self.sock:
234 raise socket.error, msg
Martin v. Löwisa43c2f82001-07-24 20:34:08 +0000235 (code, msg) = self.getreply()
236 if self.debuglevel > 0: print "connect:", msg
237 return (code, msg)
Tim Peters495ad3c2001-01-15 01:36:40 +0000238
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000239 def send(self, str):
240 """Send `str' to the server."""
241 if self.debuglevel > 0: print 'send:', `str`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 if self.sock:
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000243 try:
Barry Warsaw5bf94a02000-09-01 06:40:07 +0000244 sendptr = 0
245 while sendptr < len(str):
246 sendptr = sendptr + self.sock.send(str[sendptr:])
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000247 except socket.error:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000248 raise SMTPServerDisconnected('Server not connected')
Guido van Rossumfc40a831998-01-29 17:26:45 +0000249 else:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000250 raise SMTPServerDisconnected('please run connect() first')
Tim Peters495ad3c2001-01-15 01:36:40 +0000251
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000252 def putcmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000253 """Send a command to the server."""
Guido van Rossumdb23d3d1999-06-09 15:13:10 +0000254 if args == "":
255 str = '%s%s' % (cmd, CRLF)
256 else:
257 str = '%s %s%s' % (cmd, args, CRLF)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000258 self.send(str)
Tim Peters495ad3c2001-01-15 01:36:40 +0000259
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000260 def getreply(self):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000261 """Get a reply from the server.
Tim Peters495ad3c2001-01-15 01:36:40 +0000262
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000263 Returns a tuple consisting of:
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000264
265 - server response code (e.g. '250', or such, if all goes well)
266 Note: returns -1 if it can't read response code.
267
268 - server response string corresponding to response code (multiline
269 responses are converted to a single, multiline string).
Guido van Rossumf123f841999-03-29 20:33:21 +0000270
271 Raises SMTPServerDisconnected if end-of-file is reached.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000272 """
273 resp=[]
Guido van Rossum296e1431999-04-07 15:03:39 +0000274 if self.file is None:
275 self.file = self.sock.makefile('rb')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 while 1:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000277 line = self.file.readline()
Guido van Rossum296e1431999-04-07 15:03:39 +0000278 if line == '':
279 self.close()
280 raise SMTPServerDisconnected("Connection unexpectedly closed")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000281 if self.debuglevel > 0: print 'reply:', `line`
Eric S. Raymondc013f302001-02-09 05:40:38 +0000282 resp.append(line[4:].strip())
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 code=line[:3]
Guido van Rossum296e1431999-04-07 15:03:39 +0000284 # Check that the error code is syntactically correct.
285 # Don't attempt to read a continuation line if it is broken.
286 try:
Eric S. Raymondc013f302001-02-09 05:40:38 +0000287 errcode = int(code)
Guido van Rossum296e1431999-04-07 15:03:39 +0000288 except ValueError:
289 errcode = -1
290 break
Guido van Rossumf123f841999-03-29 20:33:21 +0000291 # Check if multiline response.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000292 if line[3:4]!="-":
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000293 break
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000294
Eric S. Raymondc013f302001-02-09 05:40:38 +0000295 errmsg = "\n".join(resp)
Tim Peters495ad3c2001-01-15 01:36:40 +0000296 if self.debuglevel > 0:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000297 print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000298 return errcode, errmsg
Tim Peters495ad3c2001-01-15 01:36:40 +0000299
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000300 def docmd(self, cmd, args=""):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000301 """Send a command, and return its response code."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000302 self.putcmd(cmd,args)
Guido van Rossum296e1431999-04-07 15:03:39 +0000303 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000304
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000305 # std smtp commands
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000306 def helo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000307 """SMTP 'helo' command.
308 Hostname to send for this command defaults to the FQDN of the local
309 host.
310 """
Thomas Wouterscaa658d2000-08-15 19:30:36 +0000311 if name:
312 self.putcmd("helo", name)
313 else:
Fred Drake0ebc1c62000-08-16 14:26:22 +0000314 self.putcmd("helo", socket.getfqdn())
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000315 (code,msg)=self.getreply()
316 self.helo_resp=msg
Guido van Rossum296e1431999-04-07 15:03:39 +0000317 return (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000318
Guido van Rossum95e6f701998-06-25 02:15:50 +0000319 def ehlo(self, name=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000320 """ SMTP 'ehlo' command.
321 Hostname to send for this command defaults to the FQDN of the local
322 host.
323 """
Thomas Wouterscaa658d2000-08-15 19:30:36 +0000324 if name:
325 self.putcmd("ehlo", name)
326 else:
Fred Drake0ebc1c62000-08-16 14:26:22 +0000327 self.putcmd("ehlo", socket.getfqdn())
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000328 (code,msg)=self.getreply()
Tim Peters495ad3c2001-01-15 01:36:40 +0000329 # According to RFC1869 some (badly written)
330 # MTA's will disconnect on an ehlo. Toss an exception if
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000331 # that happens -ddm
332 if code == -1 and len(msg) == 0:
Guido van Rossum40233ea1999-01-15 03:23:55 +0000333 raise SMTPServerDisconnected("Server not connected")
Guido van Rossum95e6f701998-06-25 02:15:50 +0000334 self.ehlo_resp=msg
Fred Drake8152d322000-12-12 23:20:45 +0000335 if code != 250:
Guido van Rossum296e1431999-04-07 15:03:39 +0000336 return (code,msg)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000337 self.does_esmtp=1
Thomas Wouters7e474022000-07-16 12:04:32 +0000338 #parse the ehlo response -ddm
Eric S. Raymondc013f302001-02-09 05:40:38 +0000339 resp=self.ehlo_resp.split('\n')
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000340 del resp[0]
Guido van Rossum2880f6e1998-08-10 20:07:00 +0000341 for each in resp:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000342 m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
343 if m:
Eric S. Raymondc013f302001-02-09 05:40:38 +0000344 feature=m.group("feature").lower()
345 params=m.string[m.end("feature"):].strip()
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000346 self.esmtp_features[feature]=params
Guido van Rossum296e1431999-04-07 15:03:39 +0000347 return (code,msg)
Guido van Rossum95e6f701998-06-25 02:15:50 +0000348
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000349 def has_extn(self, opt):
350 """Does the server support a given SMTP service extension?"""
Eric S. Raymondc013f302001-02-09 05:40:38 +0000351 return self.esmtp_features.has_key(opt.lower())
Guido van Rossum95e6f701998-06-25 02:15:50 +0000352
Guido van Rossum18586f41998-04-03 17:03:13 +0000353 def help(self, args=''):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000354 """SMTP 'help' command.
355 Returns help text from server."""
Guido van Rossum18586f41998-04-03 17:03:13 +0000356 self.putcmd("help", args)
Guido van Rossum296e1431999-04-07 15:03:39 +0000357 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000358
359 def rset(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000360 """SMTP 'rset' command -- resets session."""
Guido van Rossum296e1431999-04-07 15:03:39 +0000361 return self.docmd("rset")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000362
363 def noop(self):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000364 """SMTP 'noop' command -- doesn't do anything :>"""
Guido van Rossum296e1431999-04-07 15:03:39 +0000365 return self.docmd("noop")
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000366
Guido van Rossum95e6f701998-06-25 02:15:50 +0000367 def mail(self,sender,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000368 """SMTP 'mail' command -- begins mail xfer session."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000369 optionlist = ''
370 if options and self.does_esmtp:
Eric S. Raymondc013f302001-02-09 05:40:38 +0000371 optionlist = ' ' + ' '.join(options)
Guido van Rossumdb23d3d1999-06-09 15:13:10 +0000372 self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000373 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000374
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000375 def rcpt(self,recip,options=[]):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000376 """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000377 optionlist = ''
378 if options and self.does_esmtp:
Eric S. Raymondc013f302001-02-09 05:40:38 +0000379 optionlist = ' ' + ' '.join(options)
Guido van Rossum348fd061999-01-14 04:18:46 +0000380 self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000382
383 def data(self,msg):
Tim Peters495ad3c2001-01-15 01:36:40 +0000384 """SMTP 'DATA' command -- sends message data to server.
Guido van Rossum296e1431999-04-07 15:03:39 +0000385
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000386 Automatically quotes lines beginning with a period per rfc821.
Guido van Rossum296e1431999-04-07 15:03:39 +0000387 Raises SMTPDataError if there is an unexpected reply to the
388 DATA command; the return value from this method is the final
389 response code received when the all data is sent.
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000390 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 self.putcmd("data")
392 (code,repl)=self.getreply()
393 if self.debuglevel >0 : print "data:", (code,repl)
Fred Drake8152d322000-12-12 23:20:45 +0000394 if code != 354:
Guido van Rossum296e1431999-04-07 15:03:39 +0000395 raise SMTPDataError(code,repl)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 else:
Guido van Rossum20c92281999-04-21 16:52:20 +0000397 q = quotedata(msg)
398 if q[-2:] != CRLF:
399 q = q + CRLF
400 q = q + "." + CRLF
401 self.send(q)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000402 (code,msg)=self.getreply()
403 if self.debuglevel >0 : print "data:", (code,msg)
Guido van Rossum296e1431999-04-07 15:03:39 +0000404 return (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000405
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000406 def verify(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000407 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000408 self.putcmd("vrfy", quoteaddr(address))
409 return self.getreply()
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000410 # a.k.a.
411 vrfy=verify
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000412
413 def expn(self, address):
Barry Warsawa7d9bdf1998-12-22 03:24:27 +0000414 """SMTP 'verify' command -- checks for address validity."""
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000415 self.putcmd("expn", quoteaddr(address))
416 return self.getreply()
417
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000418 # some useful methods
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000419 def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
Tim Peters495ad3c2001-01-15 01:36:40 +0000420 rcpt_options=[]):
421 """This command performs an entire mail transaction.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000422
Tim Peters495ad3c2001-01-15 01:36:40 +0000423 The arguments are:
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000424 - from_addr : The address sending this mail.
425 - to_addrs : A list of addresses to send this mail to. A bare
426 string will be treated as a list with 1 address.
Tim Peters495ad3c2001-01-15 01:36:40 +0000427 - msg : The message to send.
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000428 - mail_options : List of ESMTP options (such as 8bitmime) for the
429 mail command.
430 - rcpt_options : List of ESMTP options (such as DSN commands) for
431 all the rcpt commands.
432
433 If there has been no previous EHLO or HELO command this session, this
434 method tries ESMTP EHLO first. If the server does ESMTP, message size
435 and each of the specified options will be passed to it. If EHLO
436 fails, HELO will be tried and ESMTP options suppressed.
437
438 This method will return normally if the mail is accepted for at least
Barry Warsawd25c1b71999-11-28 17:11:06 +0000439 one recipient. It returns a dictionary, with one entry for each
440 recipient that was refused. Each entry contains a tuple of the SMTP
441 error code and the accompanying error message sent by the server.
Guido van Rossum296e1431999-04-07 15:03:39 +0000442
443 This method may raise the following exceptions:
444
445 SMTPHeloError The server didn't reply properly to
Tim Peters495ad3c2001-01-15 01:36:40 +0000446 the helo greeting.
Barry Warsawd25c1b71999-11-28 17:11:06 +0000447 SMTPRecipientsRefused The server rejected ALL recipients
Guido van Rossum296e1431999-04-07 15:03:39 +0000448 (no mail was sent).
449 SMTPSenderRefused The server didn't accept the from_addr.
450 SMTPDataError The server replied with an unexpected
451 error code (other than a refusal of
452 a recipient).
453
454 Note: the connection will be open even after an exception is raised.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000455
Guido van Rossum95e6f701998-06-25 02:15:50 +0000456 Example:
Tim Peters495ad3c2001-01-15 01:36:40 +0000457
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000458 >>> import smtplib
459 >>> s=smtplib.SMTP("localhost")
Guido van Rossumfc40a831998-01-29 17:26:45 +0000460 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000461 >>> msg = '''
462 ... From: Me@my.org
463 ... Subject: testin'...
464 ...
465 ... This is a test '''
466 >>> s.sendmail("me@my.org",tolist,msg)
467 { "three@three.org" : ( 550 ,"User unknown" ) }
468 >>> s.quit()
Tim Peters495ad3c2001-01-15 01:36:40 +0000469
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000470 In the above example, the message was accepted for delivery to three
471 of the four addresses, and one was rejected, with the error code
Barry Warsawd25c1b71999-11-28 17:11:06 +0000472 550. If all addresses are accepted, then the method will return an
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000473 empty dictionary.
474
475 """
Guido van Rossum296e1431999-04-07 15:03:39 +0000476 if self.helo_resp is None and self.ehlo_resp is None:
477 if not (200 <= self.ehlo()[0] <= 299):
478 (code,resp) = self.helo()
479 if not (200 <= code <= 299):
480 raise SMTPHeloError(code, resp)
Guido van Rossum95e6f701998-06-25 02:15:50 +0000481 esmtp_opts = []
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000482 if self.does_esmtp:
483 # Hmmm? what's this? -ddm
484 # self.esmtp_features['7bit']=""
485 if self.has_extn('size'):
486 esmtp_opts.append("size=" + `len(msg)`)
487 for option in mail_options:
Guido van Rossum95e6f701998-06-25 02:15:50 +0000488 esmtp_opts.append(option)
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000489
Guido van Rossum95e6f701998-06-25 02:15:50 +0000490 (code,resp) = self.mail(from_addr, esmtp_opts)
Fred Drake8152d322000-12-12 23:20:45 +0000491 if code != 250:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000493 raise SMTPSenderRefused(code, resp, from_addr)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000494 senderrs={}
Jeremy Hylton31bb8ce1998-08-13 19:57:46 +0000495 if type(to_addrs) == types.StringType:
496 to_addrs = [to_addrs]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000497 for each in to_addrs:
Guido van Rossumfcfb6321998-08-04 15:29:54 +0000498 (code,resp)=self.rcpt(each, rcpt_options)
Fred Drake8152d322000-12-12 23:20:45 +0000499 if (code != 250) and (code != 251):
Guido van Rossumfc40a831998-01-29 17:26:45 +0000500 senderrs[each]=(code,resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000501 if len(senderrs)==len(to_addrs):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000502 # the server refused all our recipients
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000503 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000504 raise SMTPRecipientsRefused(senderrs)
Fred Drake8152d322000-12-12 23:20:45 +0000505 (code,resp) = self.data(msg)
506 if code != 250:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000507 self.rset()
Guido van Rossum296e1431999-04-07 15:03:39 +0000508 raise SMTPDataError(code, resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000509 #if we got here then somebody got our mail
Tim Peters495ad3c2001-01-15 01:36:40 +0000510 return senderrs
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000511
512
513 def close(self):
514 """Close the connection to the SMTP server."""
515 if self.file:
516 self.file.close()
517 self.file = None
518 if self.sock:
519 self.sock.close()
520 self.sock = None
521
522
523 def quit(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000524 """Terminate the SMTP session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000525 self.docmd("quit")
526 self.close()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000527
Barry Warsaw4c4bec81998-12-22 03:02:20 +0000528
Guido van Rossum95e6f701998-06-25 02:15:50 +0000529# Test the sendmail method, which tests most of the others.
530# Note: This always sends to localhost.
531if __name__ == '__main__':
532 import sys, rfc822
533
534 def prompt(prompt):
535 sys.stdout.write(prompt + ": ")
Eric S. Raymondc013f302001-02-09 05:40:38 +0000536 return sys.stdin.readline().strip()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000537
538 fromaddr = prompt("From")
Eric S. Raymond38151ed2001-02-09 07:40:17 +0000539 toaddrs = prompt("To").split(',')
Guido van Rossum95e6f701998-06-25 02:15:50 +0000540 print "Enter message, end with ^D:"
541 msg = ''
542 while 1:
543 line = sys.stdin.readline()
544 if not line:
545 break
546 msg = msg + line
547 print "Message length is " + `len(msg)`
548
549 server = SMTP('localhost')
550 server.set_debuglevel(1)
551 server.sendmail(fromaddr, toaddrs, msg)
552 server.quit()