blob: 95c0f966ff6f50c1dbda971e84ff84ecdf63ab66 [file] [log] [blame]
Guido van Rossum95e6f701998-06-25 02:15:50 +00001#!/usr/bin/python
2"""SMTP/ESMTP client class.
Guido van Rossumbbe323e1998-01-29 17:24:40 +00003
4Author: The Dragon De Monsyne <dragondm@integral.org>
Guido van Rossum95e6f701998-06-25 02:15:50 +00005ESMTP support, test code and doc fixes added by
6Eric S. Raymond <esr@thyrsus.com>
Guido van Rossumbbe323e1998-01-29 17:24:40 +00007
8(This was modified from the Python 1.5 library HTTP lib.)
9
Guido van Rossum95e6f701998-06-25 02:15:50 +000010This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
Guido van Rossumbbe323e1998-01-29 17:24:40 +000011
12Example:
13
14>>> import smtplib
15>>> s=smtplib.SMTP("localhost")
16>>> print s.help()
17This is Sendmail version 8.8.4
18Topics:
19 HELO EHLO MAIL RCPT DATA
20 RSET NOOP QUIT HELP VRFY
21 EXPN VERB ETRN DSN
22For more info use "HELP <topic>".
23To report bugs in the implementation send email to
24 sendmail-bugs@sendmail.org.
25For local information send email to Postmaster at your site.
26End of HELP info
27>>> s.putcmd("vrfy","someone@here")
28>>> s.getreply()
29(250, "Somebody OverHere <somebody@here.my.org>")
30>>> s.quit()
31
32"""
33
34import socket
35import string,re
36
37SMTP_PORT = 25
38CRLF="\r\n"
39
40# used for exceptions
Guido van Rossumfc40a831998-01-29 17:26:45 +000041SMTPServerDisconnected="Server not connected"
Guido van Rossumbbe323e1998-01-29 17:24:40 +000042SMTPSenderRefused="Sender address refused"
43SMTPRecipientsRefused="All Recipients refused"
Guido van Rossum95e6f701998-06-25 02:15:50 +000044SMTPDataError="Error transmitting message data"
Guido van Rossumbbe323e1998-01-29 17:24:40 +000045
46class SMTP:
Guido van Rossum95e6f701998-06-25 02:15:50 +000047 """This class manages a connection to an SMTP or ESMTP server."""
48 debuglevel = 0
49 file = None
50 helo_resp = None
51 ehlo_resp = None
52 esmtp_features = []
53
Guido van Rossumbbe323e1998-01-29 17:24:40 +000054 def __init__(self, host = '', port = 0):
55 """Initialize a new instance.
56
57 If specified, `host' is the name of the remote host to which
58 to connect. If specified, `port' specifies the port to which
59 to connect. By default, smtplib.SMTP_PORT is used.
60
61 """
Guido van Rossumbbe323e1998-01-29 17:24:40 +000062 if host: self.connect(host, port)
63
64 def set_debuglevel(self, debuglevel):
65 """Set the debug output level.
66
67 A non-false value results in debug messages for connection and
68 for all messages sent to and received from the server.
69
70 """
71 self.debuglevel = debuglevel
72
Guido van Rossum95e6f701998-06-25 02:15:50 +000073 def verify(self, address):
74 """ SMTP 'verify' command. Checks for address validity. """
75 self.putcmd("vrfy", address)
76 return self.getreply()
77
Guido van Rossumbbe323e1998-01-29 17:24:40 +000078 def connect(self, host='localhost', port = 0):
79 """Connect to a host on a given port.
Guido van Rossum95e6f701998-06-25 02:15:50 +000080
81 If the hostname ends with a colon (`:') followed by a number,
82 that suffix will be stripped off and the number interpreted as
83 the port number to use.
84
Guido van Rossumbbe323e1998-01-29 17:24:40 +000085 Note: This method is automatically invoked by __init__,
86 if a host is specified during instantiation.
87
88 """
89 if not port:
90 i = string.find(host, ':')
91 if i >= 0:
92 host, port = host[:i], host[i+1:]
93 try: port = string.atoi(port)
94 except string.atoi_error:
95 raise socket.error, "nonnumeric port"
96 if not port: port = SMTP_PORT
97 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
98 if self.debuglevel > 0: print 'connect:', (host, port)
99 self.sock.connect(host, port)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 (code,msg)=self.getreply()
101 if self.debuglevel >0 : print "connect:", msg
102 return msg
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000103
104 def send(self, str):
105 """Send `str' to the server."""
106 if self.debuglevel > 0: print 'send:', `str`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 if self.sock:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000108 self.sock.send(str)
109 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 raise SMTPServerDisconnected
Guido van Rossumfc40a831998-01-29 17:26:45 +0000111
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000112 def putcmd(self, cmd, args=""):
113 """Send a command to the server.
114 """
115 str = '%s %s%s' % (cmd, args, CRLF)
116 self.send(str)
117
Guido van Rossum95e6f701998-06-25 02:15:50 +0000118 def getreply(self, linehook=None):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000119 """Get a reply from the server.
120
121 Returns a tuple consisting of:
122 - server response code (e.g. '250', or such, if all goes well)
Guido van Rossum95e6f701998-06-25 02:15:50 +0000123 Note: returns -1 if it can't read response code.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000124 - server response string corresponding to response code
Guido van Rossum95e6f701998-06-25 02:15:50 +0000125 (note : multiline responses converted to a single,
Guido van Rossumfc40a831998-01-29 17:26:45 +0000126 multiline string)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000127 """
128 resp=[]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000129 self.file = self.sock.makefile('rb')
130 while 1:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000131 line = self.file.readline()
132 if self.debuglevel > 0: print 'reply:', `line`
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 resp.append(string.strip(line[4:]))
134 code=line[:3]
135 #check if multiline resp
136 if line[3:4]!="-":
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000137 break
Guido van Rossum95e6f701998-06-25 02:15:50 +0000138 elif linehook:
139 linehook(line)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000140 try:
141 errcode = string.atoi(code)
142 except(ValueError):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000143 errcode = -1
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000144
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 errmsg = string.join(resp,"\n")
146 if self.debuglevel > 0:
Guido van Rossumfc40a831998-01-29 17:26:45 +0000147 print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000148 return errcode, errmsg
149
150 def docmd(self, cmd, args=""):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000151 """ Send a command, and return its response code """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152
153 self.putcmd(cmd,args)
154 (code,msg)=self.getreply()
155 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000156# std smtp commands
157
158 def helo(self, name=''):
159 """ SMTP 'helo' command. Hostname to send for this command
160 defaults to the FQDN of the local host """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 name=string.strip(name)
162 if len(name)==0:
163 name=socket.gethostbyaddr(socket.gethostname())[0]
164 self.putcmd("helo",name)
165 (code,msg)=self.getreply()
166 self.helo_resp=msg
167 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000168
Guido van Rossum95e6f701998-06-25 02:15:50 +0000169 def ehlo(self, name=''):
170 """ SMTP 'ehlo' command. Hostname to send for this command
171 defaults to the FQDN of the local host """
172 name=string.strip(name)
173 if len(name)==0:
174 name=socket.gethostbyaddr(socket.gethostname())[0]
175 self.putcmd("ehlo",name)
176 (code,msg)=self.getreply(self.ehlo_hook)
177 self.ehlo_resp=msg
178 return code
179
180 def ehlo_hook(self, line):
181 # Interpret EHLO response lines
182 if line[4] in string.uppercase+string.digits:
183 self.esmtp_features.append(string.lower(string.strip(line)[4:]))
184
185 def has_option(self, opt):
186 """Does the server support a given SMTP option?"""
187 return opt in self.esmtp_features
188
Guido van Rossum18586f41998-04-03 17:03:13 +0000189 def help(self, args=''):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 """ SMTP 'help' command. Returns help text from server """
Guido van Rossum18586f41998-04-03 17:03:13 +0000191 self.putcmd("help", args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 (code,msg)=self.getreply()
193 return msg
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000194
195 def rset(self):
196 """ SMTP 'rset' command. Resets session. """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 code=self.docmd("rset")
198 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000199
200 def noop(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000201 """ SMTP 'noop' command. Doesn't do anything :> """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 code=self.docmd("noop")
203 return code
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000204
Guido van Rossum95e6f701998-06-25 02:15:50 +0000205 def mail(self,sender,options=[]):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000206 """ SMTP 'mail' command. Begins mail xfer session. """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000207 if options:
208 options = " " + string.joinfields(options, ' ')
209 else:
210 options = ''
211 self.putcmd("mail from:", sender + options)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000213
214 def rcpt(self,recip):
215 """ SMTP 'rcpt' command. Indicates 1 recipient for this mail. """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000216 self.putcmd("rcpt","to: %s" % recip)
217 return self.getreply()
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000218
219 def data(self,msg):
220 """ SMTP 'DATA' command. Sends message data to server.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000221 Automatically quotes lines beginning with a period per rfc821. """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000222 #quote periods in msg according to RFC821
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000223 # ps, I don't know why I have to do it this way... doing:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 # quotepat=re.compile(r"^[.]",re.M)
225 # msg=re.sub(quotepat,"..",msg)
Guido van Rossumfc40a831998-01-29 17:26:45 +0000226 # should work, but it dosen't (it doubles the number of any
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000227 # contiguous series of .'s at the beginning of a line,
Guido van Rossumfc40a831998-01-29 17:26:45 +0000228 #instead of just adding one. )
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 quotepat=re.compile(r"^[.]+",re.M)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000230 def m(pat):
231 return "."+pat.group(0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000232 msg=re.sub(quotepat,m,msg)
233 self.putcmd("data")
234 (code,repl)=self.getreply()
235 if self.debuglevel >0 : print "data:", (code,repl)
236 if code <> 354:
237 return -1
238 else:
239 self.send(msg)
240 self.send("\n.\n")
241 (code,msg)=self.getreply()
242 if self.debuglevel >0 : print "data:", (code,msg)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000243 return code
244
Guido van Rossum95e6f701998-06-25 02:15:50 +0000245#some useful methods
246 def sendmail(self,from_addr,to_addrs,msg,options=[]):
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000247 """ This command performs an entire mail transaction.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 The arguments are:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000249 - from_addr : The address sending this mail.
250 - to_addrs : a list of addresses to send this mail to
251 - msg : the message to send.
Guido van Rossum95e6f701998-06-25 02:15:50 +0000252 - encoding : list of ESMTP options (such as 8bitmime)
253
254 If there has been no previous EHLO or HELO command this session,
255 this method tries ESMTP EHLO first. If the server does ESMTP, message
256 size and each of the specified options will be passed to it (if the
257 option is in the feature set the server advertises). If EHLO fails,
258 HELO will be tried and ESMTP options suppressed.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000259
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 This method will return normally if the mail is accepted for at least
Guido van Rossum95e6f701998-06-25 02:15:50 +0000261 one recipient. Otherwise it will throw an exception (either
262 SMTPSenderRefused, SMTPRecipientsRefused, or SMTPDataError)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 That is, if this method does not throw an exception, then someone
Guido van Rossum95e6f701998-06-25 02:15:50 +0000264 should get your mail. If this method does not throw an exception,
265 it returns a dictionary, with one entry for each recipient that was
Guido van Rossumfc40a831998-01-29 17:26:45 +0000266 refused.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000267
Guido van Rossum95e6f701998-06-25 02:15:50 +0000268 Example:
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000269
270 >>> import smtplib
271 >>> s=smtplib.SMTP("localhost")
Guido van Rossumfc40a831998-01-29 17:26:45 +0000272 >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000273 >>> msg = '''
274 ... From: Me@my.org
275 ... Subject: testin'...
276 ...
277 ... This is a test '''
278 >>> s.sendmail("me@my.org",tolist,msg)
279 { "three@three.org" : ( 550 ,"User unknown" ) }
280 >>> s.quit()
281
Guido van Rossumfc40a831998-01-29 17:26:45 +0000282 In the above example, the message was accepted for delivery to
283 three of the four addresses, and one was rejected, with the error
284 code 550. If all addresses are accepted, then the method
285 will return an empty dictionary.
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000286 """
Guido van Rossum95e6f701998-06-25 02:15:50 +0000287 if not self.helo_resp and not self.ehlo_resp:
288 if self.ehlo() >= 400:
289 self.helo()
290 if self.esmtp_features:
291 self.esmtp_features.append('7bit')
292 esmtp_opts = []
293 if 'size' in self.esmtp_features:
294 esmtp_opts.append("size=" + `len(msg)`)
295 for option in options:
296 if option in self.esmtp_features:
297 esmtp_opts.append(option)
298 (code,resp) = self.mail(from_addr, esmtp_opts)
299 if code <> 250:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000300 self.rset()
301 raise SMTPSenderRefused
302 senderrs={}
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000303 for each in to_addrs:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000304 (code,resp)=self.rcpt(each)
305 if (code <> 250) and (code <> 251):
Guido van Rossumfc40a831998-01-29 17:26:45 +0000306 senderrs[each]=(code,resp)
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000307 if len(senderrs)==len(to_addrs):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000308 # the server refused all our recipients
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000309 self.rset()
310 raise SMTPRecipientsRefused
311 code=self.data(msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000312 if code <>250 :
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000313 self.rset()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000314 raise SMTPDataError
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000315 #if we got here then somebody got our mail
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000316 return senderrs
Guido van Rossumbbe323e1998-01-29 17:24:40 +0000317
318
319 def close(self):
320 """Close the connection to the SMTP server."""
321 if self.file:
322 self.file.close()
323 self.file = None
324 if self.sock:
325 self.sock.close()
326 self.sock = None
327
328
329 def quit(self):
Guido van Rossum95e6f701998-06-25 02:15:50 +0000330 """Terminate the SMTP session."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000331 self.docmd("quit")
332 self.close()
Guido van Rossum95e6f701998-06-25 02:15:50 +0000333
334# Test the sendmail method, which tests most of the others.
335# Note: This always sends to localhost.
336if __name__ == '__main__':
337 import sys, rfc822
338
339 def prompt(prompt):
340 sys.stdout.write(prompt + ": ")
341 return string.strip(sys.stdin.readline())
342
343 fromaddr = prompt("From")
344 toaddrs = string.splitfields(prompt("To"), ',')
345 print "Enter message, end with ^D:"
346 msg = ''
347 while 1:
348 line = sys.stdin.readline()
349 if not line:
350 break
351 msg = msg + line
352 print "Message length is " + `len(msg)`
353
354 server = SMTP('localhost')
355 server.set_debuglevel(1)
356 server.sendmail(fromaddr, toaddrs, msg)
357 server.quit()
358
359