smtplib.py 44 KB

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