smtplib.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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 = False
  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 = True
  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, *, 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 context parameter,
  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 None:
  656. context = ssl._create_stdlib_context()
  657. self.sock = context.wrap_socket(self.sock,
  658. server_hostname=self._host)
  659. self.file = None
  660. # RFC 3207:
  661. # The client MUST discard any knowledge obtained from
  662. # the server, such as the list of SMTP service extensions,
  663. # which was not obtained from the TLS negotiation itself.
  664. self.helo_resp = None
  665. self.ehlo_resp = None
  666. self.esmtp_features = {}
  667. self.does_esmtp = False
  668. else:
  669. # RFC 3207:
  670. # 501 Syntax error (no parameters allowed)
  671. # 454 TLS not available due to temporary reason
  672. raise SMTPResponseException(resp, reply)
  673. return (resp, reply)
  674. def sendmail(self, from_addr, to_addrs, msg, mail_options=(),
  675. rcpt_options=()):
  676. """This command performs an entire mail transaction.
  677. The arguments are:
  678. - from_addr : The address sending this mail.
  679. - to_addrs : A list of addresses to send this mail to. A bare
  680. string will be treated as a list with 1 address.
  681. - msg : The message to send.
  682. - mail_options : List of ESMTP options (such as 8bitmime) for the
  683. mail command.
  684. - rcpt_options : List of ESMTP options (such as DSN commands) for
  685. all the rcpt commands.
  686. msg may be a string containing characters in the ASCII range, or a byte
  687. string. A string is encoded to bytes using the ascii codec, and lone
  688. \\r and \\n characters are converted to \\r\\n characters.
  689. If there has been no previous EHLO or HELO command this session, this
  690. method tries ESMTP EHLO first. If the server does ESMTP, message size
  691. and each of the specified options will be passed to it. If EHLO
  692. fails, HELO will be tried and ESMTP options suppressed.
  693. This method will return normally if the mail is accepted for at least
  694. one recipient. It returns a dictionary, with one entry for each
  695. recipient that was refused. Each entry contains a tuple of the SMTP
  696. error code and the accompanying error message sent by the server.
  697. This method may raise the following exceptions:
  698. SMTPHeloError The server didn't reply properly to
  699. the helo greeting.
  700. SMTPRecipientsRefused The server rejected ALL recipients
  701. (no mail was sent).
  702. SMTPSenderRefused The server didn't accept the from_addr.
  703. SMTPDataError The server replied with an unexpected
  704. error code (other than a refusal of
  705. a recipient).
  706. SMTPNotSupportedError The mail_options parameter includes 'SMTPUTF8'
  707. but the SMTPUTF8 extension is not supported by
  708. the server.
  709. Note: the connection will be open even after an exception is raised.
  710. Example:
  711. >>> import smtplib
  712. >>> s=smtplib.SMTP("localhost")
  713. >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  714. >>> msg = '''\\
  715. ... From: Me@my.org
  716. ... Subject: testin'...
  717. ...
  718. ... This is a test '''
  719. >>> s.sendmail("me@my.org",tolist,msg)
  720. { "three@three.org" : ( 550 ,"User unknown" ) }
  721. >>> s.quit()
  722. In the above example, the message was accepted for delivery to three
  723. of the four addresses, and one was rejected, with the error code
  724. 550. If all addresses are accepted, then the method will return an
  725. empty dictionary.
  726. """
  727. self.ehlo_or_helo_if_needed()
  728. esmtp_opts = []
  729. if isinstance(msg, str):
  730. msg = _fix_eols(msg).encode('ascii')
  731. if self.does_esmtp:
  732. if self.has_extn('size'):
  733. esmtp_opts.append("size=%d" % len(msg))
  734. for option in mail_options:
  735. esmtp_opts.append(option)
  736. (code, resp) = self.mail(from_addr, esmtp_opts)
  737. if code != 250:
  738. if code == 421:
  739. self.close()
  740. else:
  741. self._rset()
  742. raise SMTPSenderRefused(code, resp, from_addr)
  743. senderrs = {}
  744. if isinstance(to_addrs, str):
  745. to_addrs = [to_addrs]
  746. for each in to_addrs:
  747. (code, resp) = self.rcpt(each, rcpt_options)
  748. if (code != 250) and (code != 251):
  749. senderrs[each] = (code, resp)
  750. if code == 421:
  751. self.close()
  752. raise SMTPRecipientsRefused(senderrs)
  753. if len(senderrs) == len(to_addrs):
  754. # the server refused all our recipients
  755. self._rset()
  756. raise SMTPRecipientsRefused(senderrs)
  757. (code, resp) = self.data(msg)
  758. if code != 250:
  759. if code == 421:
  760. self.close()
  761. else:
  762. self._rset()
  763. raise SMTPDataError(code, resp)
  764. #if we got here then somebody got our mail
  765. return senderrs
  766. def send_message(self, msg, from_addr=None, to_addrs=None,
  767. mail_options=(), rcpt_options=()):
  768. """Converts message to a bytestring and passes it to sendmail.
  769. The arguments are as for sendmail, except that msg is an
  770. email.message.Message object. If from_addr is None or to_addrs is
  771. None, these arguments are taken from the headers of the Message as
  772. described in RFC 2822 (a ValueError is raised if there is more than
  773. one set of 'Resent-' headers). Regardless of the values of from_addr and
  774. to_addr, any Bcc field (or Resent-Bcc field, when the Message is a
  775. resent) of the Message object won't be transmitted. The Message
  776. object is then serialized using email.generator.BytesGenerator and
  777. sendmail is called to transmit the message. If the sender or any of
  778. the recipient addresses contain non-ASCII and the server advertises the
  779. SMTPUTF8 capability, the policy is cloned with utf8 set to True for the
  780. serialization, and SMTPUTF8 and BODY=8BITMIME are asserted on the send.
  781. If the server does not support SMTPUTF8, an SMTPNotSupported error is
  782. raised. Otherwise the generator is called without modifying the
  783. policy.
  784. """
  785. # 'Resent-Date' is a mandatory field if the Message is resent (RFC 2822
  786. # Section 3.6.6). In such a case, we use the 'Resent-*' fields. However,
  787. # if there is more than one 'Resent-' block there's no way to
  788. # unambiguously determine which one is the most recent in all cases,
  789. # so rather than guess we raise a ValueError in that case.
  790. #
  791. # TODO implement heuristics to guess the correct Resent-* block with an
  792. # option allowing the user to enable the heuristics. (It should be
  793. # possible to guess correctly almost all of the time.)
  794. self.ehlo_or_helo_if_needed()
  795. resent = msg.get_all('Resent-Date')
  796. if resent is None:
  797. header_prefix = ''
  798. elif len(resent) == 1:
  799. header_prefix = 'Resent-'
  800. else:
  801. raise ValueError("message has more than one 'Resent-' header block")
  802. if from_addr is None:
  803. # Prefer the sender field per RFC 2822:3.6.2.
  804. from_addr = (msg[header_prefix + 'Sender']
  805. if (header_prefix + 'Sender') in msg
  806. else msg[header_prefix + 'From'])
  807. from_addr = email.utils.getaddresses([from_addr])[0][1]
  808. if to_addrs is None:
  809. addr_fields = [f for f in (msg[header_prefix + 'To'],
  810. msg[header_prefix + 'Bcc'],
  811. msg[header_prefix + 'Cc'])
  812. if f is not None]
  813. to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
  814. # Make a local copy so we can delete the bcc headers.
  815. msg_copy = copy.copy(msg)
  816. del msg_copy['Bcc']
  817. del msg_copy['Resent-Bcc']
  818. international = False
  819. try:
  820. ''.join([from_addr, *to_addrs]).encode('ascii')
  821. except UnicodeEncodeError:
  822. if not self.has_extn('smtputf8'):
  823. raise SMTPNotSupportedError(
  824. "One or more source or delivery addresses require"
  825. " internationalized email support, but the server"
  826. " does not advertise the required SMTPUTF8 capability")
  827. international = True
  828. with io.BytesIO() as bytesmsg:
  829. if international:
  830. g = email.generator.BytesGenerator(
  831. bytesmsg, policy=msg.policy.clone(utf8=True))
  832. mail_options = (*mail_options, 'SMTPUTF8', 'BODY=8BITMIME')
  833. else:
  834. g = email.generator.BytesGenerator(bytesmsg)
  835. g.flatten(msg_copy, linesep='\r\n')
  836. flatmsg = bytesmsg.getvalue()
  837. return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
  838. rcpt_options)
  839. def close(self):
  840. """Close the connection to the SMTP server."""
  841. try:
  842. file = self.file
  843. self.file = None
  844. if file:
  845. file.close()
  846. finally:
  847. sock = self.sock
  848. self.sock = None
  849. if sock:
  850. sock.close()
  851. def quit(self):
  852. """Terminate the SMTP session."""
  853. res = self.docmd("quit")
  854. # A new EHLO is required after reconnecting with connect()
  855. self.ehlo_resp = self.helo_resp = None
  856. self.esmtp_features = {}
  857. self.does_esmtp = False
  858. self.close()
  859. return res
  860. if _have_ssl:
  861. class SMTP_SSL(SMTP):
  862. """ This is a subclass derived from SMTP that connects over an SSL
  863. encrypted socket (to use this class you need a socket module that was
  864. compiled with SSL support). If host is not specified, '' (the local
  865. host) is used. If port is omitted, the standard SMTP-over-SSL port
  866. (465) is used. local_hostname and source_address have the same meaning
  867. as they do in the SMTP class. context also optional, can contain a
  868. SSLContext.
  869. """
  870. default_port = SMTP_SSL_PORT
  871. def __init__(self, host='', port=0, local_hostname=None,
  872. *, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  873. source_address=None, context=None):
  874. if context is None:
  875. context = ssl._create_stdlib_context()
  876. self.context = context
  877. SMTP.__init__(self, host, port, local_hostname, timeout,
  878. source_address)
  879. def _get_socket(self, host, port, timeout):
  880. if self.debuglevel > 0:
  881. self._print_debug('connect:', (host, port))
  882. new_socket = super()._get_socket(host, port, timeout)
  883. new_socket = self.context.wrap_socket(new_socket,
  884. server_hostname=self._host)
  885. return new_socket
  886. __all__.append("SMTP_SSL")
  887. #
  888. # LMTP extension
  889. #
  890. LMTP_PORT = 2003
  891. class LMTP(SMTP):
  892. """LMTP - Local Mail Transfer Protocol
  893. The LMTP protocol, which is very similar to ESMTP, is heavily based
  894. on the standard SMTP client. It's common to use Unix sockets for
  895. LMTP, so our connect() method must support that as well as a regular
  896. host:port server. local_hostname and source_address have the same
  897. meaning as they do in the SMTP class. To specify a Unix socket,
  898. you must use an absolute path as the host, starting with a '/'.
  899. Authentication is supported, using the regular SMTP mechanism. When
  900. using a Unix socket, LMTP generally don't support or require any
  901. authentication, but your mileage might vary."""
  902. ehlo_msg = "lhlo"
  903. def __init__(self, host='', port=LMTP_PORT, local_hostname=None,
  904. source_address=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
  905. """Initialize a new instance."""
  906. super().__init__(host, port, local_hostname=local_hostname,
  907. source_address=source_address, timeout=timeout)
  908. def connect(self, host='localhost', port=0, source_address=None):
  909. """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
  910. if host[0] != '/':
  911. return super().connect(host, port, source_address=source_address)
  912. if self.timeout is not None and not self.timeout:
  913. raise ValueError('Non-blocking socket (timeout=0) is not supported')
  914. # Handle Unix-domain sockets.
  915. try:
  916. self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  917. if self.timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  918. self.sock.settimeout(self.timeout)
  919. self.file = None
  920. self.sock.connect(host)
  921. except OSError:
  922. if self.debuglevel > 0:
  923. self._print_debug('connect fail:', host)
  924. if self.sock:
  925. self.sock.close()
  926. self.sock = None
  927. raise
  928. (code, msg) = self.getreply()
  929. if self.debuglevel > 0:
  930. self._print_debug('connect:', msg)
  931. return (code, msg)
  932. # Test the sendmail method, which tests most of the others.
  933. # Note: This always sends to localhost.
  934. if __name__ == '__main__':
  935. def prompt(prompt):
  936. sys.stdout.write(prompt + ": ")
  937. sys.stdout.flush()
  938. return sys.stdin.readline().strip()
  939. fromaddr = prompt("From")
  940. toaddrs = prompt("To").split(',')
  941. print("Enter message, end with ^D:")
  942. msg = ''
  943. while line := sys.stdin.readline():
  944. msg = msg + line
  945. print("Message length is %d" % len(msg))
  946. server = SMTP('localhost')
  947. server.set_debuglevel(1)
  948. server.sendmail(fromaddr, toaddrs, msg)
  949. server.quit()