1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | '''SMTP/ESMTP client class. |
---|
4 | n/a | |
---|
5 | n/a | This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP |
---|
6 | n/a | Authentication) and RFC 2487 (Secure SMTP over TLS). |
---|
7 | n/a | |
---|
8 | n/a | Notes: |
---|
9 | n/a | |
---|
10 | n/a | Please remember, when doing ESMTP, that the names of the SMTP service |
---|
11 | n/a | extensions are NOT the same thing as the option keywords for the RCPT |
---|
12 | n/a | and MAIL commands! |
---|
13 | n/a | |
---|
14 | n/a | Example: |
---|
15 | n/a | |
---|
16 | n/a | >>> import smtplib |
---|
17 | n/a | >>> s=smtplib.SMTP("localhost") |
---|
18 | n/a | >>> print(s.help()) |
---|
19 | n/a | This is Sendmail version 8.8.4 |
---|
20 | n/a | Topics: |
---|
21 | n/a | HELO EHLO MAIL RCPT DATA |
---|
22 | n/a | RSET NOOP QUIT HELP VRFY |
---|
23 | n/a | EXPN VERB ETRN DSN |
---|
24 | n/a | For more info use "HELP <topic>". |
---|
25 | n/a | To report bugs in the implementation send email to |
---|
26 | n/a | sendmail-bugs@sendmail.org. |
---|
27 | n/a | For local information send email to Postmaster at your site. |
---|
28 | n/a | End of HELP info |
---|
29 | n/a | >>> s.putcmd("vrfy","someone@here") |
---|
30 | n/a | >>> s.getreply() |
---|
31 | n/a | (250, "Somebody OverHere <somebody@here.my.org>") |
---|
32 | n/a | >>> s.quit() |
---|
33 | n/a | ''' |
---|
34 | n/a | |
---|
35 | n/a | # Author: The Dragon De Monsyne <dragondm@integral.org> |
---|
36 | n/a | # ESMTP support, test code and doc fixes added by |
---|
37 | n/a | # Eric S. Raymond <esr@thyrsus.com> |
---|
38 | n/a | # Better RFC 821 compliance (MAIL and RCPT, and CRLF in data) |
---|
39 | n/a | # by Carey Evans <c.evans@clear.net.nz>, for picky mail servers. |
---|
40 | n/a | # RFC 2554 (authentication) support by Gerhard Haering <gerhard@bigfoot.de>. |
---|
41 | n/a | # |
---|
42 | n/a | # This was modified from the Python 1.5 library HTTP lib. |
---|
43 | n/a | |
---|
44 | n/a | import socket |
---|
45 | n/a | import io |
---|
46 | n/a | import re |
---|
47 | n/a | import email.utils |
---|
48 | n/a | import email.message |
---|
49 | n/a | import email.generator |
---|
50 | n/a | import base64 |
---|
51 | n/a | import hmac |
---|
52 | n/a | import copy |
---|
53 | n/a | import datetime |
---|
54 | n/a | import sys |
---|
55 | n/a | from email.base64mime import body_encode as encode_base64 |
---|
56 | n/a | |
---|
57 | n/a | __all__ = ["SMTPException", "SMTPServerDisconnected", "SMTPResponseException", |
---|
58 | n/a | "SMTPSenderRefused", "SMTPRecipientsRefused", "SMTPDataError", |
---|
59 | n/a | "SMTPConnectError", "SMTPHeloError", "SMTPAuthenticationError", |
---|
60 | n/a | "quoteaddr", "quotedata", "SMTP"] |
---|
61 | n/a | |
---|
62 | n/a | SMTP_PORT = 25 |
---|
63 | n/a | SMTP_SSL_PORT = 465 |
---|
64 | n/a | CRLF = "\r\n" |
---|
65 | n/a | bCRLF = b"\r\n" |
---|
66 | n/a | _MAXLINE = 8192 # more than 8 times larger than RFC 821, 4.5.3 |
---|
67 | n/a | |
---|
68 | n/a | OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I) |
---|
69 | n/a | |
---|
70 | n/a | # Exception classes used by this module. |
---|
71 | n/a | class SMTPException(OSError): |
---|
72 | n/a | """Base class for all exceptions raised by this module.""" |
---|
73 | n/a | |
---|
74 | n/a | class SMTPNotSupportedError(SMTPException): |
---|
75 | n/a | """The command or option is not supported by the SMTP server. |
---|
76 | n/a | |
---|
77 | n/a | This exception is raised when an attempt is made to run a command or a |
---|
78 | n/a | command with an option which is not supported by the server. |
---|
79 | n/a | """ |
---|
80 | n/a | |
---|
81 | n/a | class SMTPServerDisconnected(SMTPException): |
---|
82 | n/a | """Not connected to any SMTP server. |
---|
83 | n/a | |
---|
84 | n/a | This exception is raised when the server unexpectedly disconnects, |
---|
85 | n/a | or when an attempt is made to use the SMTP instance before |
---|
86 | n/a | connecting it to a server. |
---|
87 | n/a | """ |
---|
88 | n/a | |
---|
89 | n/a | class SMTPResponseException(SMTPException): |
---|
90 | n/a | """Base class for all exceptions that include an SMTP error code. |
---|
91 | n/a | |
---|
92 | n/a | These exceptions are generated in some instances when the SMTP |
---|
93 | n/a | server returns an error code. The error code is stored in the |
---|
94 | n/a | `smtp_code' attribute of the error, and the `smtp_error' attribute |
---|
95 | n/a | is set to the error message. |
---|
96 | n/a | """ |
---|
97 | n/a | |
---|
98 | n/a | def __init__(self, code, msg): |
---|
99 | n/a | self.smtp_code = code |
---|
100 | n/a | self.smtp_error = msg |
---|
101 | n/a | self.args = (code, msg) |
---|
102 | n/a | |
---|
103 | n/a | class SMTPSenderRefused(SMTPResponseException): |
---|
104 | n/a | """Sender address refused. |
---|
105 | n/a | |
---|
106 | n/a | In addition to the attributes set by on all SMTPResponseException |
---|
107 | n/a | exceptions, this sets `sender' to the string that the SMTP refused. |
---|
108 | n/a | """ |
---|
109 | n/a | |
---|
110 | n/a | def __init__(self, code, msg, sender): |
---|
111 | n/a | self.smtp_code = code |
---|
112 | n/a | self.smtp_error = msg |
---|
113 | n/a | self.sender = sender |
---|
114 | n/a | self.args = (code, msg, sender) |
---|
115 | n/a | |
---|
116 | n/a | class SMTPRecipientsRefused(SMTPException): |
---|
117 | n/a | """All recipient addresses refused. |
---|
118 | n/a | |
---|
119 | n/a | The errors for each recipient are accessible through the attribute |
---|
120 | n/a | 'recipients', which is a dictionary of exactly the same sort as |
---|
121 | n/a | SMTP.sendmail() returns. |
---|
122 | n/a | """ |
---|
123 | n/a | |
---|
124 | n/a | def __init__(self, recipients): |
---|
125 | n/a | self.recipients = recipients |
---|
126 | n/a | self.args = (recipients,) |
---|
127 | n/a | |
---|
128 | n/a | |
---|
129 | n/a | class SMTPDataError(SMTPResponseException): |
---|
130 | n/a | """The SMTP server didn't accept the data.""" |
---|
131 | n/a | |
---|
132 | n/a | class SMTPConnectError(SMTPResponseException): |
---|
133 | n/a | """Error during connection establishment.""" |
---|
134 | n/a | |
---|
135 | n/a | class SMTPHeloError(SMTPResponseException): |
---|
136 | n/a | """The server refused our HELO reply.""" |
---|
137 | n/a | |
---|
138 | n/a | class SMTPAuthenticationError(SMTPResponseException): |
---|
139 | n/a | """Authentication error. |
---|
140 | n/a | |
---|
141 | n/a | Most probably the server didn't accept the username/password |
---|
142 | n/a | combination provided. |
---|
143 | n/a | """ |
---|
144 | n/a | |
---|
145 | n/a | def quoteaddr(addrstring): |
---|
146 | n/a | """Quote a subset of the email addresses defined by RFC 821. |
---|
147 | n/a | |
---|
148 | n/a | Should be able to handle anything email.utils.parseaddr can handle. |
---|
149 | n/a | """ |
---|
150 | n/a | displayname, addr = email.utils.parseaddr(addrstring) |
---|
151 | n/a | if (displayname, addr) == ('', ''): |
---|
152 | n/a | # parseaddr couldn't parse it, use it as is and hope for the best. |
---|
153 | n/a | if addrstring.strip().startswith('<'): |
---|
154 | n/a | return addrstring |
---|
155 | n/a | return "<%s>" % addrstring |
---|
156 | n/a | return "<%s>" % addr |
---|
157 | n/a | |
---|
158 | n/a | def _addr_only(addrstring): |
---|
159 | n/a | displayname, addr = email.utils.parseaddr(addrstring) |
---|
160 | n/a | if (displayname, addr) == ('', ''): |
---|
161 | n/a | # parseaddr couldn't parse it, so use it as is. |
---|
162 | n/a | return addrstring |
---|
163 | n/a | return addr |
---|
164 | n/a | |
---|
165 | n/a | # Legacy method kept for backward compatibility. |
---|
166 | n/a | def quotedata(data): |
---|
167 | n/a | """Quote data for email. |
---|
168 | n/a | |
---|
169 | n/a | Double leading '.', and change Unix newline '\\n', or Mac '\\r' into |
---|
170 | n/a | Internet CRLF end-of-line. |
---|
171 | n/a | """ |
---|
172 | n/a | return re.sub(r'(?m)^\.', '..', |
---|
173 | n/a | re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data)) |
---|
174 | n/a | |
---|
175 | n/a | def _quote_periods(bindata): |
---|
176 | n/a | return re.sub(br'(?m)^\.', b'..', bindata) |
---|
177 | n/a | |
---|
178 | n/a | def _fix_eols(data): |
---|
179 | n/a | return re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data) |
---|
180 | n/a | |
---|
181 | n/a | try: |
---|
182 | n/a | import ssl |
---|
183 | n/a | except ImportError: |
---|
184 | n/a | _have_ssl = False |
---|
185 | n/a | else: |
---|
186 | n/a | _have_ssl = True |
---|
187 | n/a | |
---|
188 | n/a | |
---|
189 | n/a | class SMTP: |
---|
190 | n/a | """This class manages a connection to an SMTP or ESMTP server. |
---|
191 | n/a | SMTP Objects: |
---|
192 | n/a | SMTP objects have the following attributes: |
---|
193 | n/a | helo_resp |
---|
194 | n/a | This is the message given by the server in response to the |
---|
195 | n/a | most recent HELO command. |
---|
196 | n/a | |
---|
197 | n/a | ehlo_resp |
---|
198 | n/a | This is the message given by the server in response to the |
---|
199 | n/a | most recent EHLO command. This is usually multiline. |
---|
200 | n/a | |
---|
201 | n/a | does_esmtp |
---|
202 | n/a | This is a True value _after you do an EHLO command_, if the |
---|
203 | n/a | server supports ESMTP. |
---|
204 | n/a | |
---|
205 | n/a | esmtp_features |
---|
206 | n/a | This is a dictionary, which, if the server supports ESMTP, |
---|
207 | n/a | will _after you do an EHLO command_, contain the names of the |
---|
208 | n/a | SMTP service extensions this server supports, and their |
---|
209 | n/a | parameters (if any). |
---|
210 | n/a | |
---|
211 | n/a | Note, all extension names are mapped to lower case in the |
---|
212 | n/a | dictionary. |
---|
213 | n/a | |
---|
214 | n/a | See each method's docstrings for details. In general, there is a |
---|
215 | n/a | method of the same name to perform each SMTP command. There is also a |
---|
216 | n/a | method called 'sendmail' that will do an entire mail transaction. |
---|
217 | n/a | """ |
---|
218 | n/a | debuglevel = 0 |
---|
219 | n/a | file = None |
---|
220 | n/a | helo_resp = None |
---|
221 | n/a | ehlo_msg = "ehlo" |
---|
222 | n/a | ehlo_resp = None |
---|
223 | n/a | does_esmtp = 0 |
---|
224 | n/a | default_port = SMTP_PORT |
---|
225 | n/a | |
---|
226 | n/a | def __init__(self, host='', port=0, local_hostname=None, |
---|
227 | n/a | timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
---|
228 | n/a | source_address=None): |
---|
229 | n/a | """Initialize a new instance. |
---|
230 | n/a | |
---|
231 | n/a | If specified, `host' is the name of the remote host to which to |
---|
232 | n/a | connect. If specified, `port' specifies the port to which to connect. |
---|
233 | n/a | By default, smtplib.SMTP_PORT is used. If a host is specified the |
---|
234 | n/a | connect method is called, and if it returns anything other than a |
---|
235 | n/a | success code an SMTPConnectError is raised. If specified, |
---|
236 | n/a | `local_hostname` is used as the FQDN of the local host in the HELO/EHLO |
---|
237 | n/a | command. Otherwise, the local hostname is found using |
---|
238 | n/a | socket.getfqdn(). The `source_address` parameter takes a 2-tuple (host, |
---|
239 | n/a | port) for the socket to bind to as its source address before |
---|
240 | n/a | connecting. If the host is '' and port is 0, the OS default behavior |
---|
241 | n/a | will be used. |
---|
242 | n/a | |
---|
243 | n/a | """ |
---|
244 | n/a | self._host = host |
---|
245 | n/a | self.timeout = timeout |
---|
246 | n/a | self.esmtp_features = {} |
---|
247 | n/a | self.command_encoding = 'ascii' |
---|
248 | n/a | self.source_address = source_address |
---|
249 | n/a | |
---|
250 | n/a | if host: |
---|
251 | n/a | (code, msg) = self.connect(host, port) |
---|
252 | n/a | if code != 220: |
---|
253 | n/a | raise SMTPConnectError(code, msg) |
---|
254 | n/a | if local_hostname is not None: |
---|
255 | n/a | self.local_hostname = local_hostname |
---|
256 | n/a | else: |
---|
257 | n/a | # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and |
---|
258 | n/a | # if that can't be calculated, that we should use a domain literal |
---|
259 | n/a | # instead (essentially an encoded IP address like [A.B.C.D]). |
---|
260 | n/a | fqdn = socket.getfqdn() |
---|
261 | n/a | if '.' in fqdn: |
---|
262 | n/a | self.local_hostname = fqdn |
---|
263 | n/a | else: |
---|
264 | n/a | # We can't find an fqdn hostname, so use a domain literal |
---|
265 | n/a | addr = '127.0.0.1' |
---|
266 | n/a | try: |
---|
267 | n/a | addr = socket.gethostbyname(socket.gethostname()) |
---|
268 | n/a | except socket.gaierror: |
---|
269 | n/a | pass |
---|
270 | n/a | self.local_hostname = '[%s]' % addr |
---|
271 | n/a | |
---|
272 | n/a | def __enter__(self): |
---|
273 | n/a | return self |
---|
274 | n/a | |
---|
275 | n/a | def __exit__(self, *args): |
---|
276 | n/a | try: |
---|
277 | n/a | code, message = self.docmd("QUIT") |
---|
278 | n/a | if code != 221: |
---|
279 | n/a | raise SMTPResponseException(code, message) |
---|
280 | n/a | except SMTPServerDisconnected: |
---|
281 | n/a | pass |
---|
282 | n/a | finally: |
---|
283 | n/a | self.close() |
---|
284 | n/a | |
---|
285 | n/a | def set_debuglevel(self, debuglevel): |
---|
286 | n/a | """Set the debug output level. |
---|
287 | n/a | |
---|
288 | n/a | A non-false value results in debug messages for connection and for all |
---|
289 | n/a | messages sent to and received from the server. |
---|
290 | n/a | |
---|
291 | n/a | """ |
---|
292 | n/a | self.debuglevel = debuglevel |
---|
293 | n/a | |
---|
294 | n/a | def _print_debug(self, *args): |
---|
295 | n/a | if self.debuglevel > 1: |
---|
296 | n/a | print(datetime.datetime.now().time(), *args, file=sys.stderr) |
---|
297 | n/a | else: |
---|
298 | n/a | print(*args, file=sys.stderr) |
---|
299 | n/a | |
---|
300 | n/a | def _get_socket(self, host, port, timeout): |
---|
301 | n/a | # This makes it simpler for SMTP_SSL to use the SMTP connect code |
---|
302 | n/a | # and just alter the socket connection bit. |
---|
303 | n/a | if self.debuglevel > 0: |
---|
304 | n/a | self._print_debug('connect: to', (host, port), self.source_address) |
---|
305 | n/a | return socket.create_connection((host, port), timeout, |
---|
306 | n/a | self.source_address) |
---|
307 | n/a | |
---|
308 | n/a | def connect(self, host='localhost', port=0, source_address=None): |
---|
309 | n/a | """Connect to a host on a given port. |
---|
310 | n/a | |
---|
311 | n/a | If the hostname ends with a colon (`:') followed by a number, and |
---|
312 | n/a | there is no port specified, that suffix will be stripped off and the |
---|
313 | n/a | number interpreted as the port number to use. |
---|
314 | n/a | |
---|
315 | n/a | Note: This method is automatically invoked by __init__, if a host is |
---|
316 | n/a | specified during instantiation. |
---|
317 | n/a | |
---|
318 | n/a | """ |
---|
319 | n/a | |
---|
320 | n/a | if source_address: |
---|
321 | n/a | self.source_address = source_address |
---|
322 | n/a | |
---|
323 | n/a | if not port and (host.find(':') == host.rfind(':')): |
---|
324 | n/a | i = host.rfind(':') |
---|
325 | n/a | if i >= 0: |
---|
326 | n/a | host, port = host[:i], host[i + 1:] |
---|
327 | n/a | try: |
---|
328 | n/a | port = int(port) |
---|
329 | n/a | except ValueError: |
---|
330 | n/a | raise OSError("nonnumeric port") |
---|
331 | n/a | if not port: |
---|
332 | n/a | port = self.default_port |
---|
333 | n/a | if self.debuglevel > 0: |
---|
334 | n/a | self._print_debug('connect:', (host, port)) |
---|
335 | n/a | self.sock = self._get_socket(host, port, self.timeout) |
---|
336 | n/a | self.file = None |
---|
337 | n/a | (code, msg) = self.getreply() |
---|
338 | n/a | if self.debuglevel > 0: |
---|
339 | n/a | self._print_debug('connect:', repr(msg)) |
---|
340 | n/a | return (code, msg) |
---|
341 | n/a | |
---|
342 | n/a | def send(self, s): |
---|
343 | n/a | """Send `s' to the server.""" |
---|
344 | n/a | if self.debuglevel > 0: |
---|
345 | n/a | self._print_debug('send:', repr(s)) |
---|
346 | n/a | if hasattr(self, 'sock') and self.sock: |
---|
347 | n/a | if isinstance(s, str): |
---|
348 | n/a | # send is used by the 'data' command, where command_encoding |
---|
349 | n/a | # should not be used, but 'data' needs to convert the string to |
---|
350 | n/a | # binary itself anyway, so that's not a problem. |
---|
351 | n/a | s = s.encode(self.command_encoding) |
---|
352 | n/a | try: |
---|
353 | n/a | self.sock.sendall(s) |
---|
354 | n/a | except OSError: |
---|
355 | n/a | self.close() |
---|
356 | n/a | raise SMTPServerDisconnected('Server not connected') |
---|
357 | n/a | else: |
---|
358 | n/a | raise SMTPServerDisconnected('please run connect() first') |
---|
359 | n/a | |
---|
360 | n/a | def putcmd(self, cmd, args=""): |
---|
361 | n/a | """Send a command to the server.""" |
---|
362 | n/a | if args == "": |
---|
363 | n/a | str = '%s%s' % (cmd, CRLF) |
---|
364 | n/a | else: |
---|
365 | n/a | str = '%s %s%s' % (cmd, args, CRLF) |
---|
366 | n/a | self.send(str) |
---|
367 | n/a | |
---|
368 | n/a | def getreply(self): |
---|
369 | n/a | """Get a reply from the server. |
---|
370 | n/a | |
---|
371 | n/a | Returns a tuple consisting of: |
---|
372 | n/a | |
---|
373 | n/a | - server response code (e.g. '250', or such, if all goes well) |
---|
374 | n/a | Note: returns -1 if it can't read response code. |
---|
375 | n/a | |
---|
376 | n/a | - server response string corresponding to response code (multiline |
---|
377 | n/a | responses are converted to a single, multiline string). |
---|
378 | n/a | |
---|
379 | n/a | Raises SMTPServerDisconnected if end-of-file is reached. |
---|
380 | n/a | """ |
---|
381 | n/a | resp = [] |
---|
382 | n/a | if self.file is None: |
---|
383 | n/a | self.file = self.sock.makefile('rb') |
---|
384 | n/a | while 1: |
---|
385 | n/a | try: |
---|
386 | n/a | line = self.file.readline(_MAXLINE + 1) |
---|
387 | n/a | except OSError as e: |
---|
388 | n/a | self.close() |
---|
389 | n/a | raise SMTPServerDisconnected("Connection unexpectedly closed: " |
---|
390 | n/a | + str(e)) |
---|
391 | n/a | if not line: |
---|
392 | n/a | self.close() |
---|
393 | n/a | raise SMTPServerDisconnected("Connection unexpectedly closed") |
---|
394 | n/a | if self.debuglevel > 0: |
---|
395 | n/a | self._print_debug('reply:', repr(line)) |
---|
396 | n/a | if len(line) > _MAXLINE: |
---|
397 | n/a | self.close() |
---|
398 | n/a | raise SMTPResponseException(500, "Line too long.") |
---|
399 | n/a | resp.append(line[4:].strip(b' \t\r\n')) |
---|
400 | n/a | code = line[:3] |
---|
401 | n/a | # Check that the error code is syntactically correct. |
---|
402 | n/a | # Don't attempt to read a continuation line if it is broken. |
---|
403 | n/a | try: |
---|
404 | n/a | errcode = int(code) |
---|
405 | n/a | except ValueError: |
---|
406 | n/a | errcode = -1 |
---|
407 | n/a | break |
---|
408 | n/a | # Check if multiline response. |
---|
409 | n/a | if line[3:4] != b"-": |
---|
410 | n/a | break |
---|
411 | n/a | |
---|
412 | n/a | errmsg = b"\n".join(resp) |
---|
413 | n/a | if self.debuglevel > 0: |
---|
414 | n/a | self._print_debug('reply: retcode (%s); Msg: %a' % (errcode, errmsg)) |
---|
415 | n/a | return errcode, errmsg |
---|
416 | n/a | |
---|
417 | n/a | def docmd(self, cmd, args=""): |
---|
418 | n/a | """Send a command, and return its response code.""" |
---|
419 | n/a | self.putcmd(cmd, args) |
---|
420 | n/a | return self.getreply() |
---|
421 | n/a | |
---|
422 | n/a | # std smtp commands |
---|
423 | n/a | def helo(self, name=''): |
---|
424 | n/a | """SMTP 'helo' command. |
---|
425 | n/a | Hostname to send for this command defaults to the FQDN of the local |
---|
426 | n/a | host. |
---|
427 | n/a | """ |
---|
428 | n/a | self.putcmd("helo", name or self.local_hostname) |
---|
429 | n/a | (code, msg) = self.getreply() |
---|
430 | n/a | self.helo_resp = msg |
---|
431 | n/a | return (code, msg) |
---|
432 | n/a | |
---|
433 | n/a | def ehlo(self, name=''): |
---|
434 | n/a | """ SMTP 'ehlo' command. |
---|
435 | n/a | Hostname to send for this command defaults to the FQDN of the local |
---|
436 | n/a | host. |
---|
437 | n/a | """ |
---|
438 | n/a | self.esmtp_features = {} |
---|
439 | n/a | self.putcmd(self.ehlo_msg, name or self.local_hostname) |
---|
440 | n/a | (code, msg) = self.getreply() |
---|
441 | n/a | # According to RFC1869 some (badly written) |
---|
442 | n/a | # MTA's will disconnect on an ehlo. Toss an exception if |
---|
443 | n/a | # that happens -ddm |
---|
444 | n/a | if code == -1 and len(msg) == 0: |
---|
445 | n/a | self.close() |
---|
446 | n/a | raise SMTPServerDisconnected("Server not connected") |
---|
447 | n/a | self.ehlo_resp = msg |
---|
448 | n/a | if code != 250: |
---|
449 | n/a | return (code, msg) |
---|
450 | n/a | self.does_esmtp = 1 |
---|
451 | n/a | #parse the ehlo response -ddm |
---|
452 | n/a | assert isinstance(self.ehlo_resp, bytes), repr(self.ehlo_resp) |
---|
453 | n/a | resp = self.ehlo_resp.decode("latin-1").split('\n') |
---|
454 | n/a | del resp[0] |
---|
455 | n/a | for each in resp: |
---|
456 | n/a | # To be able to communicate with as many SMTP servers as possible, |
---|
457 | n/a | # we have to take the old-style auth advertisement into account, |
---|
458 | n/a | # because: |
---|
459 | n/a | # 1) Else our SMTP feature parser gets confused. |
---|
460 | n/a | # 2) There are some servers that only advertise the auth methods we |
---|
461 | n/a | # support using the old style. |
---|
462 | n/a | auth_match = OLDSTYLE_AUTH.match(each) |
---|
463 | n/a | if auth_match: |
---|
464 | n/a | # This doesn't remove duplicates, but that's no problem |
---|
465 | n/a | self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \ |
---|
466 | n/a | + " " + auth_match.groups(0)[0] |
---|
467 | n/a | continue |
---|
468 | n/a | |
---|
469 | n/a | # RFC 1869 requires a space between ehlo keyword and parameters. |
---|
470 | n/a | # It's actually stricter, in that only spaces are allowed between |
---|
471 | n/a | # parameters, but were not going to check for that here. Note |
---|
472 | n/a | # that the space isn't present if there are no parameters. |
---|
473 | n/a | m = re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?', each) |
---|
474 | n/a | if m: |
---|
475 | n/a | feature = m.group("feature").lower() |
---|
476 | n/a | params = m.string[m.end("feature"):].strip() |
---|
477 | n/a | if feature == "auth": |
---|
478 | n/a | self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \ |
---|
479 | n/a | + " " + params |
---|
480 | n/a | else: |
---|
481 | n/a | self.esmtp_features[feature] = params |
---|
482 | n/a | return (code, msg) |
---|
483 | n/a | |
---|
484 | n/a | def has_extn(self, opt): |
---|
485 | n/a | """Does the server support a given SMTP service extension?""" |
---|
486 | n/a | return opt.lower() in self.esmtp_features |
---|
487 | n/a | |
---|
488 | n/a | def help(self, args=''): |
---|
489 | n/a | """SMTP 'help' command. |
---|
490 | n/a | Returns help text from server.""" |
---|
491 | n/a | self.putcmd("help", args) |
---|
492 | n/a | return self.getreply()[1] |
---|
493 | n/a | |
---|
494 | n/a | def rset(self): |
---|
495 | n/a | """SMTP 'rset' command -- resets session.""" |
---|
496 | n/a | self.command_encoding = 'ascii' |
---|
497 | n/a | return self.docmd("rset") |
---|
498 | n/a | |
---|
499 | n/a | def _rset(self): |
---|
500 | n/a | """Internal 'rset' command which ignores any SMTPServerDisconnected error. |
---|
501 | n/a | |
---|
502 | n/a | Used internally in the library, since the server disconnected error |
---|
503 | n/a | should appear to the application when the *next* command is issued, if |
---|
504 | n/a | we are doing an internal "safety" reset. |
---|
505 | n/a | """ |
---|
506 | n/a | try: |
---|
507 | n/a | self.rset() |
---|
508 | n/a | except SMTPServerDisconnected: |
---|
509 | n/a | pass |
---|
510 | n/a | |
---|
511 | n/a | def noop(self): |
---|
512 | n/a | """SMTP 'noop' command -- doesn't do anything :>""" |
---|
513 | n/a | return self.docmd("noop") |
---|
514 | n/a | |
---|
515 | n/a | def mail(self, sender, options=[]): |
---|
516 | n/a | """SMTP 'mail' command -- begins mail xfer session. |
---|
517 | n/a | |
---|
518 | n/a | This method may raise the following exceptions: |
---|
519 | n/a | |
---|
520 | n/a | SMTPNotSupportedError The options parameter includes 'SMTPUTF8' |
---|
521 | n/a | but the SMTPUTF8 extension is not supported by |
---|
522 | n/a | the server. |
---|
523 | n/a | """ |
---|
524 | n/a | optionlist = '' |
---|
525 | n/a | if options and self.does_esmtp: |
---|
526 | n/a | if any(x.lower()=='smtputf8' for x in options): |
---|
527 | n/a | if self.has_extn('smtputf8'): |
---|
528 | n/a | self.command_encoding = 'utf-8' |
---|
529 | n/a | else: |
---|
530 | n/a | raise SMTPNotSupportedError( |
---|
531 | n/a | 'SMTPUTF8 not supported by server') |
---|
532 | n/a | optionlist = ' ' + ' '.join(options) |
---|
533 | n/a | self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist)) |
---|
534 | n/a | return self.getreply() |
---|
535 | n/a | |
---|
536 | n/a | def rcpt(self, recip, options=[]): |
---|
537 | n/a | """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" |
---|
538 | n/a | optionlist = '' |
---|
539 | n/a | if options and self.does_esmtp: |
---|
540 | n/a | optionlist = ' ' + ' '.join(options) |
---|
541 | n/a | self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist)) |
---|
542 | n/a | return self.getreply() |
---|
543 | n/a | |
---|
544 | n/a | def data(self, msg): |
---|
545 | n/a | """SMTP 'DATA' command -- sends message data to server. |
---|
546 | n/a | |
---|
547 | n/a | Automatically quotes lines beginning with a period per rfc821. |
---|
548 | n/a | Raises SMTPDataError if there is an unexpected reply to the |
---|
549 | n/a | DATA command; the return value from this method is the final |
---|
550 | n/a | response code received when the all data is sent. If msg |
---|
551 | n/a | is a string, lone '\\r' and '\\n' characters are converted to |
---|
552 | n/a | '\\r\\n' characters. If msg is bytes, it is transmitted as is. |
---|
553 | n/a | """ |
---|
554 | n/a | self.putcmd("data") |
---|
555 | n/a | (code, repl) = self.getreply() |
---|
556 | n/a | if self.debuglevel > 0: |
---|
557 | n/a | self._print_debug('data:', (code, repl)) |
---|
558 | n/a | if code != 354: |
---|
559 | n/a | raise SMTPDataError(code, repl) |
---|
560 | n/a | else: |
---|
561 | n/a | if isinstance(msg, str): |
---|
562 | n/a | msg = _fix_eols(msg).encode('ascii') |
---|
563 | n/a | q = _quote_periods(msg) |
---|
564 | n/a | if q[-2:] != bCRLF: |
---|
565 | n/a | q = q + bCRLF |
---|
566 | n/a | q = q + b"." + bCRLF |
---|
567 | n/a | self.send(q) |
---|
568 | n/a | (code, msg) = self.getreply() |
---|
569 | n/a | if self.debuglevel > 0: |
---|
570 | n/a | self._print_debug('data:', (code, msg)) |
---|
571 | n/a | return (code, msg) |
---|
572 | n/a | |
---|
573 | n/a | def verify(self, address): |
---|
574 | n/a | """SMTP 'verify' command -- checks for address validity.""" |
---|
575 | n/a | self.putcmd("vrfy", _addr_only(address)) |
---|
576 | n/a | return self.getreply() |
---|
577 | n/a | # a.k.a. |
---|
578 | n/a | vrfy = verify |
---|
579 | n/a | |
---|
580 | n/a | def expn(self, address): |
---|
581 | n/a | """SMTP 'expn' command -- expands a mailing list.""" |
---|
582 | n/a | self.putcmd("expn", _addr_only(address)) |
---|
583 | n/a | return self.getreply() |
---|
584 | n/a | |
---|
585 | n/a | # some useful methods |
---|
586 | n/a | |
---|
587 | n/a | def ehlo_or_helo_if_needed(self): |
---|
588 | n/a | """Call self.ehlo() and/or self.helo() if needed. |
---|
589 | n/a | |
---|
590 | n/a | If there has been no previous EHLO or HELO command this session, this |
---|
591 | n/a | method tries ESMTP EHLO first. |
---|
592 | n/a | |
---|
593 | n/a | This method may raise the following exceptions: |
---|
594 | n/a | |
---|
595 | n/a | SMTPHeloError The server didn't reply properly to |
---|
596 | n/a | the helo greeting. |
---|
597 | n/a | """ |
---|
598 | n/a | if self.helo_resp is None and self.ehlo_resp is None: |
---|
599 | n/a | if not (200 <= self.ehlo()[0] <= 299): |
---|
600 | n/a | (code, resp) = self.helo() |
---|
601 | n/a | if not (200 <= code <= 299): |
---|
602 | n/a | raise SMTPHeloError(code, resp) |
---|
603 | n/a | |
---|
604 | n/a | def auth(self, mechanism, authobject, *, initial_response_ok=True): |
---|
605 | n/a | """Authentication command - requires response processing. |
---|
606 | n/a | |
---|
607 | n/a | 'mechanism' specifies which authentication mechanism is to |
---|
608 | n/a | be used - the valid values are those listed in the 'auth' |
---|
609 | n/a | element of 'esmtp_features'. |
---|
610 | n/a | |
---|
611 | n/a | 'authobject' must be a callable object taking a single argument: |
---|
612 | n/a | |
---|
613 | n/a | data = authobject(challenge) |
---|
614 | n/a | |
---|
615 | n/a | It will be called to process the server's challenge response; the |
---|
616 | n/a | challenge argument it is passed will be a bytes. It should return |
---|
617 | n/a | bytes data that will be base64 encoded and sent to the server. |
---|
618 | n/a | |
---|
619 | n/a | Keyword arguments: |
---|
620 | n/a | - initial_response_ok: Allow sending the RFC 4954 initial-response |
---|
621 | n/a | to the AUTH command, if the authentication methods supports it. |
---|
622 | n/a | """ |
---|
623 | n/a | # RFC 4954 allows auth methods to provide an initial response. Not all |
---|
624 | n/a | # methods support it. By definition, if they return something other |
---|
625 | n/a | # than None when challenge is None, then they do. See issue #15014. |
---|
626 | n/a | mechanism = mechanism.upper() |
---|
627 | n/a | initial_response = (authobject() if initial_response_ok else None) |
---|
628 | n/a | if initial_response is not None: |
---|
629 | n/a | response = encode_base64(initial_response.encode('ascii'), eol='') |
---|
630 | n/a | (code, resp) = self.docmd("AUTH", mechanism + " " + response) |
---|
631 | n/a | else: |
---|
632 | n/a | (code, resp) = self.docmd("AUTH", mechanism) |
---|
633 | n/a | # If server responds with a challenge, send the response. |
---|
634 | n/a | if code == 334: |
---|
635 | n/a | challenge = base64.decodebytes(resp) |
---|
636 | n/a | response = encode_base64( |
---|
637 | n/a | authobject(challenge).encode('ascii'), eol='') |
---|
638 | n/a | (code, resp) = self.docmd(response) |
---|
639 | n/a | if code in (235, 503): |
---|
640 | n/a | return (code, resp) |
---|
641 | n/a | raise SMTPAuthenticationError(code, resp) |
---|
642 | n/a | |
---|
643 | n/a | def auth_cram_md5(self, challenge=None): |
---|
644 | n/a | """ Authobject to use with CRAM-MD5 authentication. Requires self.user |
---|
645 | n/a | and self.password to be set.""" |
---|
646 | n/a | # CRAM-MD5 does not support initial-response. |
---|
647 | n/a | if challenge is None: |
---|
648 | n/a | return None |
---|
649 | n/a | return self.user + " " + hmac.HMAC( |
---|
650 | n/a | self.password.encode('ascii'), challenge, 'md5').hexdigest() |
---|
651 | n/a | |
---|
652 | n/a | def auth_plain(self, challenge=None): |
---|
653 | n/a | """ Authobject to use with PLAIN authentication. Requires self.user and |
---|
654 | n/a | self.password to be set.""" |
---|
655 | n/a | return "\0%s\0%s" % (self.user, self.password) |
---|
656 | n/a | |
---|
657 | n/a | def auth_login(self, challenge=None): |
---|
658 | n/a | """ Authobject to use with LOGIN authentication. Requires self.user and |
---|
659 | n/a | self.password to be set.""" |
---|
660 | n/a | if challenge is None: |
---|
661 | n/a | return self.user |
---|
662 | n/a | else: |
---|
663 | n/a | return self.password |
---|
664 | n/a | |
---|
665 | n/a | def login(self, user, password, *, initial_response_ok=True): |
---|
666 | n/a | """Log in on an SMTP server that requires authentication. |
---|
667 | n/a | |
---|
668 | n/a | The arguments are: |
---|
669 | n/a | - user: The user name to authenticate with. |
---|
670 | n/a | - password: The password for the authentication. |
---|
671 | n/a | |
---|
672 | n/a | Keyword arguments: |
---|
673 | n/a | - initial_response_ok: Allow sending the RFC 4954 initial-response |
---|
674 | n/a | to the AUTH command, if the authentication methods supports it. |
---|
675 | n/a | |
---|
676 | n/a | If there has been no previous EHLO or HELO command this session, this |
---|
677 | n/a | method tries ESMTP EHLO first. |
---|
678 | n/a | |
---|
679 | n/a | This method will return normally if the authentication was successful. |
---|
680 | n/a | |
---|
681 | n/a | This method may raise the following exceptions: |
---|
682 | n/a | |
---|
683 | n/a | SMTPHeloError The server didn't reply properly to |
---|
684 | n/a | the helo greeting. |
---|
685 | n/a | SMTPAuthenticationError The server didn't accept the username/ |
---|
686 | n/a | password combination. |
---|
687 | n/a | SMTPNotSupportedError The AUTH command is not supported by the |
---|
688 | n/a | server. |
---|
689 | n/a | SMTPException No suitable authentication method was |
---|
690 | n/a | found. |
---|
691 | n/a | """ |
---|
692 | n/a | |
---|
693 | n/a | self.ehlo_or_helo_if_needed() |
---|
694 | n/a | if not self.has_extn("auth"): |
---|
695 | n/a | raise SMTPNotSupportedError( |
---|
696 | n/a | "SMTP AUTH extension not supported by server.") |
---|
697 | n/a | |
---|
698 | n/a | # Authentication methods the server claims to support |
---|
699 | n/a | advertised_authlist = self.esmtp_features["auth"].split() |
---|
700 | n/a | |
---|
701 | n/a | # Authentication methods we can handle in our preferred order: |
---|
702 | n/a | preferred_auths = ['CRAM-MD5', 'PLAIN', 'LOGIN'] |
---|
703 | n/a | |
---|
704 | n/a | # We try the supported authentications in our preferred order, if |
---|
705 | n/a | # the server supports them. |
---|
706 | n/a | authlist = [auth for auth in preferred_auths |
---|
707 | n/a | if auth in advertised_authlist] |
---|
708 | n/a | if not authlist: |
---|
709 | n/a | raise SMTPException("No suitable authentication method found.") |
---|
710 | n/a | |
---|
711 | n/a | # Some servers advertise authentication methods they don't really |
---|
712 | n/a | # support, so if authentication fails, we continue until we've tried |
---|
713 | n/a | # all methods. |
---|
714 | n/a | self.user, self.password = user, password |
---|
715 | n/a | for authmethod in authlist: |
---|
716 | n/a | method_name = 'auth_' + authmethod.lower().replace('-', '_') |
---|
717 | n/a | try: |
---|
718 | n/a | (code, resp) = self.auth( |
---|
719 | n/a | authmethod, getattr(self, method_name), |
---|
720 | n/a | initial_response_ok=initial_response_ok) |
---|
721 | n/a | # 235 == 'Authentication successful' |
---|
722 | n/a | # 503 == 'Error: already authenticated' |
---|
723 | n/a | if code in (235, 503): |
---|
724 | n/a | return (code, resp) |
---|
725 | n/a | except SMTPAuthenticationError as e: |
---|
726 | n/a | last_exception = e |
---|
727 | n/a | |
---|
728 | n/a | # We could not login successfully. Return result of last attempt. |
---|
729 | n/a | raise last_exception |
---|
730 | n/a | |
---|
731 | n/a | def starttls(self, keyfile=None, certfile=None, context=None): |
---|
732 | n/a | """Puts the connection to the SMTP server into TLS mode. |
---|
733 | n/a | |
---|
734 | n/a | If there has been no previous EHLO or HELO command this session, this |
---|
735 | n/a | method tries ESMTP EHLO first. |
---|
736 | n/a | |
---|
737 | n/a | If the server supports TLS, this will encrypt the rest of the SMTP |
---|
738 | n/a | session. If you provide the keyfile and certfile parameters, |
---|
739 | n/a | the identity of the SMTP server and client can be checked. This, |
---|
740 | n/a | however, depends on whether the socket module really checks the |
---|
741 | n/a | certificates. |
---|
742 | n/a | |
---|
743 | n/a | This method may raise the following exceptions: |
---|
744 | n/a | |
---|
745 | n/a | SMTPHeloError The server didn't reply properly to |
---|
746 | n/a | the helo greeting. |
---|
747 | n/a | """ |
---|
748 | n/a | self.ehlo_or_helo_if_needed() |
---|
749 | n/a | if not self.has_extn("starttls"): |
---|
750 | n/a | raise SMTPNotSupportedError( |
---|
751 | n/a | "STARTTLS extension not supported by server.") |
---|
752 | n/a | (resp, reply) = self.docmd("STARTTLS") |
---|
753 | n/a | if resp == 220: |
---|
754 | n/a | if not _have_ssl: |
---|
755 | n/a | raise RuntimeError("No SSL support included in this Python") |
---|
756 | n/a | if context is not None and keyfile is not None: |
---|
757 | n/a | raise ValueError("context and keyfile arguments are mutually " |
---|
758 | n/a | "exclusive") |
---|
759 | n/a | if context is not None and certfile is not None: |
---|
760 | n/a | raise ValueError("context and certfile arguments are mutually " |
---|
761 | n/a | "exclusive") |
---|
762 | n/a | if keyfile is not None or certfile is not None: |
---|
763 | n/a | import warnings |
---|
764 | n/a | warnings.warn("keyfile and certfile are deprecated, use a" |
---|
765 | n/a | "custom context instead", DeprecationWarning, 2) |
---|
766 | n/a | if context is None: |
---|
767 | n/a | context = ssl._create_stdlib_context(certfile=certfile, |
---|
768 | n/a | keyfile=keyfile) |
---|
769 | n/a | self.sock = context.wrap_socket(self.sock, |
---|
770 | n/a | server_hostname=self._host) |
---|
771 | n/a | self.file = None |
---|
772 | n/a | # RFC 3207: |
---|
773 | n/a | # The client MUST discard any knowledge obtained from |
---|
774 | n/a | # the server, such as the list of SMTP service extensions, |
---|
775 | n/a | # which was not obtained from the TLS negotiation itself. |
---|
776 | n/a | self.helo_resp = None |
---|
777 | n/a | self.ehlo_resp = None |
---|
778 | n/a | self.esmtp_features = {} |
---|
779 | n/a | self.does_esmtp = 0 |
---|
780 | n/a | else: |
---|
781 | n/a | # RFC 3207: |
---|
782 | n/a | # 501 Syntax error (no parameters allowed) |
---|
783 | n/a | # 454 TLS not available due to temporary reason |
---|
784 | n/a | raise SMTPResponseException(resp, reply) |
---|
785 | n/a | return (resp, reply) |
---|
786 | n/a | |
---|
787 | n/a | def sendmail(self, from_addr, to_addrs, msg, mail_options=[], |
---|
788 | n/a | rcpt_options=[]): |
---|
789 | n/a | """This command performs an entire mail transaction. |
---|
790 | n/a | |
---|
791 | n/a | The arguments are: |
---|
792 | n/a | - from_addr : The address sending this mail. |
---|
793 | n/a | - to_addrs : A list of addresses to send this mail to. A bare |
---|
794 | n/a | string will be treated as a list with 1 address. |
---|
795 | n/a | - msg : The message to send. |
---|
796 | n/a | - mail_options : List of ESMTP options (such as 8bitmime) for the |
---|
797 | n/a | mail command. |
---|
798 | n/a | - rcpt_options : List of ESMTP options (such as DSN commands) for |
---|
799 | n/a | all the rcpt commands. |
---|
800 | n/a | |
---|
801 | n/a | msg may be a string containing characters in the ASCII range, or a byte |
---|
802 | n/a | string. A string is encoded to bytes using the ascii codec, and lone |
---|
803 | n/a | \\r and \\n characters are converted to \\r\\n characters. |
---|
804 | n/a | |
---|
805 | n/a | If there has been no previous EHLO or HELO command this session, this |
---|
806 | n/a | method tries ESMTP EHLO first. If the server does ESMTP, message size |
---|
807 | n/a | and each of the specified options will be passed to it. If EHLO |
---|
808 | n/a | fails, HELO will be tried and ESMTP options suppressed. |
---|
809 | n/a | |
---|
810 | n/a | This method will return normally if the mail is accepted for at least |
---|
811 | n/a | one recipient. It returns a dictionary, with one entry for each |
---|
812 | n/a | recipient that was refused. Each entry contains a tuple of the SMTP |
---|
813 | n/a | error code and the accompanying error message sent by the server. |
---|
814 | n/a | |
---|
815 | n/a | This method may raise the following exceptions: |
---|
816 | n/a | |
---|
817 | n/a | SMTPHeloError The server didn't reply properly to |
---|
818 | n/a | the helo greeting. |
---|
819 | n/a | SMTPRecipientsRefused The server rejected ALL recipients |
---|
820 | n/a | (no mail was sent). |
---|
821 | n/a | SMTPSenderRefused The server didn't accept the from_addr. |
---|
822 | n/a | SMTPDataError The server replied with an unexpected |
---|
823 | n/a | error code (other than a refusal of |
---|
824 | n/a | a recipient). |
---|
825 | n/a | SMTPNotSupportedError The mail_options parameter includes 'SMTPUTF8' |
---|
826 | n/a | but the SMTPUTF8 extension is not supported by |
---|
827 | n/a | the server. |
---|
828 | n/a | |
---|
829 | n/a | Note: the connection will be open even after an exception is raised. |
---|
830 | n/a | |
---|
831 | n/a | Example: |
---|
832 | n/a | |
---|
833 | n/a | >>> import smtplib |
---|
834 | n/a | >>> s=smtplib.SMTP("localhost") |
---|
835 | n/a | >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"] |
---|
836 | n/a | >>> msg = '''\\ |
---|
837 | n/a | ... From: Me@my.org |
---|
838 | n/a | ... Subject: testin'... |
---|
839 | n/a | ... |
---|
840 | n/a | ... This is a test ''' |
---|
841 | n/a | >>> s.sendmail("me@my.org",tolist,msg) |
---|
842 | n/a | { "three@three.org" : ( 550 ,"User unknown" ) } |
---|
843 | n/a | >>> s.quit() |
---|
844 | n/a | |
---|
845 | n/a | In the above example, the message was accepted for delivery to three |
---|
846 | n/a | of the four addresses, and one was rejected, with the error code |
---|
847 | n/a | 550. If all addresses are accepted, then the method will return an |
---|
848 | n/a | empty dictionary. |
---|
849 | n/a | |
---|
850 | n/a | """ |
---|
851 | n/a | self.ehlo_or_helo_if_needed() |
---|
852 | n/a | esmtp_opts = [] |
---|
853 | n/a | if isinstance(msg, str): |
---|
854 | n/a | msg = _fix_eols(msg).encode('ascii') |
---|
855 | n/a | if self.does_esmtp: |
---|
856 | n/a | if self.has_extn('size'): |
---|
857 | n/a | esmtp_opts.append("size=%d" % len(msg)) |
---|
858 | n/a | for option in mail_options: |
---|
859 | n/a | esmtp_opts.append(option) |
---|
860 | n/a | (code, resp) = self.mail(from_addr, esmtp_opts) |
---|
861 | n/a | if code != 250: |
---|
862 | n/a | if code == 421: |
---|
863 | n/a | self.close() |
---|
864 | n/a | else: |
---|
865 | n/a | self._rset() |
---|
866 | n/a | raise SMTPSenderRefused(code, resp, from_addr) |
---|
867 | n/a | senderrs = {} |
---|
868 | n/a | if isinstance(to_addrs, str): |
---|
869 | n/a | to_addrs = [to_addrs] |
---|
870 | n/a | for each in to_addrs: |
---|
871 | n/a | (code, resp) = self.rcpt(each, rcpt_options) |
---|
872 | n/a | if (code != 250) and (code != 251): |
---|
873 | n/a | senderrs[each] = (code, resp) |
---|
874 | n/a | if code == 421: |
---|
875 | n/a | self.close() |
---|
876 | n/a | raise SMTPRecipientsRefused(senderrs) |
---|
877 | n/a | if len(senderrs) == len(to_addrs): |
---|
878 | n/a | # the server refused all our recipients |
---|
879 | n/a | self._rset() |
---|
880 | n/a | raise SMTPRecipientsRefused(senderrs) |
---|
881 | n/a | (code, resp) = self.data(msg) |
---|
882 | n/a | if code != 250: |
---|
883 | n/a | if code == 421: |
---|
884 | n/a | self.close() |
---|
885 | n/a | else: |
---|
886 | n/a | self._rset() |
---|
887 | n/a | raise SMTPDataError(code, resp) |
---|
888 | n/a | #if we got here then somebody got our mail |
---|
889 | n/a | return senderrs |
---|
890 | n/a | |
---|
891 | n/a | def send_message(self, msg, from_addr=None, to_addrs=None, |
---|
892 | n/a | mail_options=[], rcpt_options={}): |
---|
893 | n/a | """Converts message to a bytestring and passes it to sendmail. |
---|
894 | n/a | |
---|
895 | n/a | The arguments are as for sendmail, except that msg is an |
---|
896 | n/a | email.message.Message object. If from_addr is None or to_addrs is |
---|
897 | n/a | None, these arguments are taken from the headers of the Message as |
---|
898 | n/a | described in RFC 2822 (a ValueError is raised if there is more than |
---|
899 | n/a | one set of 'Resent-' headers). Regardless of the values of from_addr and |
---|
900 | n/a | to_addr, any Bcc field (or Resent-Bcc field, when the Message is a |
---|
901 | n/a | resent) of the Message object won't be transmitted. The Message |
---|
902 | n/a | object is then serialized using email.generator.BytesGenerator and |
---|
903 | n/a | sendmail is called to transmit the message. If the sender or any of |
---|
904 | n/a | the recipient addresses contain non-ASCII and the server advertises the |
---|
905 | n/a | SMTPUTF8 capability, the policy is cloned with utf8 set to True for the |
---|
906 | n/a | serialization, and SMTPUTF8 and BODY=8BITMIME are asserted on the send. |
---|
907 | n/a | If the server does not support SMTPUTF8, an SMTPNotSupported error is |
---|
908 | n/a | raised. Otherwise the generator is called without modifying the |
---|
909 | n/a | policy. |
---|
910 | n/a | |
---|
911 | n/a | """ |
---|
912 | n/a | # 'Resent-Date' is a mandatory field if the Message is resent (RFC 2822 |
---|
913 | n/a | # Section 3.6.6). In such a case, we use the 'Resent-*' fields. However, |
---|
914 | n/a | # if there is more than one 'Resent-' block there's no way to |
---|
915 | n/a | # unambiguously determine which one is the most recent in all cases, |
---|
916 | n/a | # so rather than guess we raise a ValueError in that case. |
---|
917 | n/a | # |
---|
918 | n/a | # TODO implement heuristics to guess the correct Resent-* block with an |
---|
919 | n/a | # option allowing the user to enable the heuristics. (It should be |
---|
920 | n/a | # possible to guess correctly almost all of the time.) |
---|
921 | n/a | |
---|
922 | n/a | self.ehlo_or_helo_if_needed() |
---|
923 | n/a | resent = msg.get_all('Resent-Date') |
---|
924 | n/a | if resent is None: |
---|
925 | n/a | header_prefix = '' |
---|
926 | n/a | elif len(resent) == 1: |
---|
927 | n/a | header_prefix = 'Resent-' |
---|
928 | n/a | else: |
---|
929 | n/a | raise ValueError("message has more than one 'Resent-' header block") |
---|
930 | n/a | if from_addr is None: |
---|
931 | n/a | # Prefer the sender field per RFC 2822:3.6.2. |
---|
932 | n/a | from_addr = (msg[header_prefix + 'Sender'] |
---|
933 | n/a | if (header_prefix + 'Sender') in msg |
---|
934 | n/a | else msg[header_prefix + 'From']) |
---|
935 | n/a | if to_addrs is None: |
---|
936 | n/a | addr_fields = [f for f in (msg[header_prefix + 'To'], |
---|
937 | n/a | msg[header_prefix + 'Bcc'], |
---|
938 | n/a | msg[header_prefix + 'Cc']) |
---|
939 | n/a | if f is not None] |
---|
940 | n/a | to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)] |
---|
941 | n/a | # Make a local copy so we can delete the bcc headers. |
---|
942 | n/a | msg_copy = copy.copy(msg) |
---|
943 | n/a | del msg_copy['Bcc'] |
---|
944 | n/a | del msg_copy['Resent-Bcc'] |
---|
945 | n/a | international = False |
---|
946 | n/a | try: |
---|
947 | n/a | ''.join([from_addr, *to_addrs]).encode('ascii') |
---|
948 | n/a | except UnicodeEncodeError: |
---|
949 | n/a | if not self.has_extn('smtputf8'): |
---|
950 | n/a | raise SMTPNotSupportedError( |
---|
951 | n/a | "One or more source or delivery addresses require" |
---|
952 | n/a | " internationalized email support, but the server" |
---|
953 | n/a | " does not advertise the required SMTPUTF8 capability") |
---|
954 | n/a | international = True |
---|
955 | n/a | with io.BytesIO() as bytesmsg: |
---|
956 | n/a | if international: |
---|
957 | n/a | g = email.generator.BytesGenerator( |
---|
958 | n/a | bytesmsg, policy=msg.policy.clone(utf8=True)) |
---|
959 | n/a | mail_options += ['SMTPUTF8', 'BODY=8BITMIME'] |
---|
960 | n/a | else: |
---|
961 | n/a | g = email.generator.BytesGenerator(bytesmsg) |
---|
962 | n/a | g.flatten(msg_copy, linesep='\r\n') |
---|
963 | n/a | flatmsg = bytesmsg.getvalue() |
---|
964 | n/a | return self.sendmail(from_addr, to_addrs, flatmsg, mail_options, |
---|
965 | n/a | rcpt_options) |
---|
966 | n/a | |
---|
967 | n/a | def close(self): |
---|
968 | n/a | """Close the connection to the SMTP server.""" |
---|
969 | n/a | try: |
---|
970 | n/a | file = self.file |
---|
971 | n/a | self.file = None |
---|
972 | n/a | if file: |
---|
973 | n/a | file.close() |
---|
974 | n/a | finally: |
---|
975 | n/a | sock = self.sock |
---|
976 | n/a | self.sock = None |
---|
977 | n/a | if sock: |
---|
978 | n/a | sock.close() |
---|
979 | n/a | |
---|
980 | n/a | def quit(self): |
---|
981 | n/a | """Terminate the SMTP session.""" |
---|
982 | n/a | res = self.docmd("quit") |
---|
983 | n/a | # A new EHLO is required after reconnecting with connect() |
---|
984 | n/a | self.ehlo_resp = self.helo_resp = None |
---|
985 | n/a | self.esmtp_features = {} |
---|
986 | n/a | self.does_esmtp = False |
---|
987 | n/a | self.close() |
---|
988 | n/a | return res |
---|
989 | n/a | |
---|
990 | n/a | if _have_ssl: |
---|
991 | n/a | |
---|
992 | n/a | class SMTP_SSL(SMTP): |
---|
993 | n/a | """ This is a subclass derived from SMTP that connects over an SSL |
---|
994 | n/a | encrypted socket (to use this class you need a socket module that was |
---|
995 | n/a | compiled with SSL support). If host is not specified, '' (the local |
---|
996 | n/a | host) is used. If port is omitted, the standard SMTP-over-SSL port |
---|
997 | n/a | (465) is used. local_hostname and source_address have the same meaning |
---|
998 | n/a | as they do in the SMTP class. keyfile and certfile are also optional - |
---|
999 | n/a | they can contain a PEM formatted private key and certificate chain file |
---|
1000 | n/a | for the SSL connection. context also optional, can contain a |
---|
1001 | n/a | SSLContext, and is an alternative to keyfile and certfile; If it is |
---|
1002 | n/a | specified both keyfile and certfile must be None. |
---|
1003 | n/a | |
---|
1004 | n/a | """ |
---|
1005 | n/a | |
---|
1006 | n/a | default_port = SMTP_SSL_PORT |
---|
1007 | n/a | |
---|
1008 | n/a | def __init__(self, host='', port=0, local_hostname=None, |
---|
1009 | n/a | keyfile=None, certfile=None, |
---|
1010 | n/a | timeout=socket._GLOBAL_DEFAULT_TIMEOUT, |
---|
1011 | n/a | source_address=None, context=None): |
---|
1012 | n/a | if context is not None and keyfile is not None: |
---|
1013 | n/a | raise ValueError("context and keyfile arguments are mutually " |
---|
1014 | n/a | "exclusive") |
---|
1015 | n/a | if context is not None and certfile is not None: |
---|
1016 | n/a | raise ValueError("context and certfile arguments are mutually " |
---|
1017 | n/a | "exclusive") |
---|
1018 | n/a | if keyfile is not None or certfile is not None: |
---|
1019 | n/a | import warnings |
---|
1020 | n/a | warnings.warn("keyfile and certfile are deprecated, use a" |
---|
1021 | n/a | "custom context instead", DeprecationWarning, 2) |
---|
1022 | n/a | self.keyfile = keyfile |
---|
1023 | n/a | self.certfile = certfile |
---|
1024 | n/a | if context is None: |
---|
1025 | n/a | context = ssl._create_stdlib_context(certfile=certfile, |
---|
1026 | n/a | keyfile=keyfile) |
---|
1027 | n/a | self.context = context |
---|
1028 | n/a | SMTP.__init__(self, host, port, local_hostname, timeout, |
---|
1029 | n/a | source_address) |
---|
1030 | n/a | |
---|
1031 | n/a | def _get_socket(self, host, port, timeout): |
---|
1032 | n/a | if self.debuglevel > 0: |
---|
1033 | n/a | self._print_debug('connect:', (host, port)) |
---|
1034 | n/a | new_socket = socket.create_connection((host, port), timeout, |
---|
1035 | n/a | self.source_address) |
---|
1036 | n/a | new_socket = self.context.wrap_socket(new_socket, |
---|
1037 | n/a | server_hostname=self._host) |
---|
1038 | n/a | return new_socket |
---|
1039 | n/a | |
---|
1040 | n/a | __all__.append("SMTP_SSL") |
---|
1041 | n/a | |
---|
1042 | n/a | # |
---|
1043 | n/a | # LMTP extension |
---|
1044 | n/a | # |
---|
1045 | n/a | LMTP_PORT = 2003 |
---|
1046 | n/a | |
---|
1047 | n/a | class LMTP(SMTP): |
---|
1048 | n/a | """LMTP - Local Mail Transfer Protocol |
---|
1049 | n/a | |
---|
1050 | n/a | The LMTP protocol, which is very similar to ESMTP, is heavily based |
---|
1051 | n/a | on the standard SMTP client. It's common to use Unix sockets for |
---|
1052 | n/a | LMTP, so our connect() method must support that as well as a regular |
---|
1053 | n/a | host:port server. local_hostname and source_address have the same |
---|
1054 | n/a | meaning as they do in the SMTP class. To specify a Unix socket, |
---|
1055 | n/a | you must use an absolute path as the host, starting with a '/'. |
---|
1056 | n/a | |
---|
1057 | n/a | Authentication is supported, using the regular SMTP mechanism. When |
---|
1058 | n/a | using a Unix socket, LMTP generally don't support or require any |
---|
1059 | n/a | authentication, but your mileage might vary.""" |
---|
1060 | n/a | |
---|
1061 | n/a | ehlo_msg = "lhlo" |
---|
1062 | n/a | |
---|
1063 | n/a | def __init__(self, host='', port=LMTP_PORT, local_hostname=None, |
---|
1064 | n/a | source_address=None): |
---|
1065 | n/a | """Initialize a new instance.""" |
---|
1066 | n/a | SMTP.__init__(self, host, port, local_hostname=local_hostname, |
---|
1067 | n/a | source_address=source_address) |
---|
1068 | n/a | |
---|
1069 | n/a | def connect(self, host='localhost', port=0, source_address=None): |
---|
1070 | n/a | """Connect to the LMTP daemon, on either a Unix or a TCP socket.""" |
---|
1071 | n/a | if host[0] != '/': |
---|
1072 | n/a | return SMTP.connect(self, host, port, source_address=source_address) |
---|
1073 | n/a | |
---|
1074 | n/a | # Handle Unix-domain sockets. |
---|
1075 | n/a | try: |
---|
1076 | n/a | self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
---|
1077 | n/a | self.file = None |
---|
1078 | n/a | self.sock.connect(host) |
---|
1079 | n/a | except OSError: |
---|
1080 | n/a | if self.debuglevel > 0: |
---|
1081 | n/a | self._print_debug('connect fail:', host) |
---|
1082 | n/a | if self.sock: |
---|
1083 | n/a | self.sock.close() |
---|
1084 | n/a | self.sock = None |
---|
1085 | n/a | raise |
---|
1086 | n/a | (code, msg) = self.getreply() |
---|
1087 | n/a | if self.debuglevel > 0: |
---|
1088 | n/a | self._print_debug('connect:', msg) |
---|
1089 | n/a | return (code, msg) |
---|
1090 | n/a | |
---|
1091 | n/a | |
---|
1092 | n/a | # Test the sendmail method, which tests most of the others. |
---|
1093 | n/a | # Note: This always sends to localhost. |
---|
1094 | n/a | if __name__ == '__main__': |
---|
1095 | n/a | def prompt(prompt): |
---|
1096 | n/a | sys.stdout.write(prompt + ": ") |
---|
1097 | n/a | sys.stdout.flush() |
---|
1098 | n/a | return sys.stdin.readline().strip() |
---|
1099 | n/a | |
---|
1100 | n/a | fromaddr = prompt("From") |
---|
1101 | n/a | toaddrs = prompt("To").split(',') |
---|
1102 | n/a | print("Enter message, end with ^D:") |
---|
1103 | n/a | msg = '' |
---|
1104 | n/a | while 1: |
---|
1105 | n/a | line = sys.stdin.readline() |
---|
1106 | n/a | if not line: |
---|
1107 | n/a | break |
---|
1108 | n/a | msg = msg + line |
---|
1109 | n/a | print("Message length is %d" % len(msg)) |
---|
1110 | n/a | |
---|
1111 | n/a | server = SMTP('localhost') |
---|
1112 | n/a | server.set_debuglevel(1) |
---|
1113 | n/a | server.sendmail(fromaddr, toaddrs, msg) |
---|
1114 | n/a | server.quit() |
---|