smtplib.py 43 KB

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