smtp.nim 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the SMTP client protocol as specified by RFC 5321,
  10. ## this can be used to send mail to any SMTP Server.
  11. ##
  12. ## This module also implements the protocol used to format messages,
  13. ## as specified by RFC 2822.
  14. ##
  15. ## Example gmail use:
  16. ##
  17. ##
  18. ## .. code-block:: Nim
  19. ## var msg = createMessage("Hello from Nim's SMTP",
  20. ## "Hello!.\n Is this awesome or what?",
  21. ## @["foo@gmail.com"])
  22. ## let smtpConn = newSmtp(useSsl = true, debug=true)
  23. ## smtpConn.connect("smtp.gmail.com", Port 465)
  24. ## smtpConn.auth("username", "password")
  25. ## smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)
  26. ##
  27. ##
  28. ## Example for startTls use:
  29. ##
  30. ##
  31. ## .. code-block:: Nim
  32. ## var msg = createMessage("Hello from Nim's SMTP",
  33. ## "Hello!.\n Is this awesome or what?",
  34. ## @["foo@gmail.com"])
  35. ## let smtpConn = newSmtp(debug=true)
  36. ## smtpConn.connect("smtp.mailtrap.io", Port 2525)
  37. ## smtpConn.startTls()
  38. ## smtpConn.auth("username", "password")
  39. ## smtpConn.sendmail("username@gmail.com", @["foo@gmail.com"], $msg)
  40. ##
  41. ##
  42. ## For SSL support this module relies on OpenSSL. If you want to
  43. ## enable SSL, compile with `-d:ssl`.
  44. import net, strutils, strtabs, base64, os, strutils
  45. import asyncnet, asyncdispatch
  46. export Port
  47. type
  48. Message* = object
  49. msgTo: seq[string]
  50. msgCc: seq[string]
  51. msgSubject: string
  52. msgOtherHeaders: StringTableRef
  53. msgBody: string
  54. ReplyError* = object of IOError
  55. SmtpBase[SocketType] = ref object
  56. sock: SocketType
  57. address: string
  58. debug: bool
  59. Smtp* = SmtpBase[Socket]
  60. AsyncSmtp* = SmtpBase[AsyncSocket]
  61. proc containsNewline(xs: seq[string]): bool =
  62. for x in xs:
  63. if x.contains({'\c', '\L'}):
  64. return true
  65. proc debugSend*(smtp: Smtp | AsyncSmtp, cmd: string) {.multisync.} =
  66. ## Sends `cmd` on the socket connected to the SMTP server.
  67. ##
  68. ## If the `smtp` object was created with `debug` enabled,
  69. ## debugSend will invoke `echo("C:" & cmd)` before sending.
  70. ##
  71. ## This is a lower level proc and not something that you typically
  72. ## would need to call when using this module. One exception to
  73. ## this is if you are implementing any
  74. ## `SMTP extensions<https://en.wikipedia.org/wiki/Extended_SMTP>`_.
  75. if smtp.debug:
  76. echo("C:" & cmd)
  77. await smtp.sock.send(cmd)
  78. proc debugRecv*(smtp: Smtp | AsyncSmtp): Future[string] {.multisync.} =
  79. ## Receives a line of data from the socket connected to the
  80. ## SMTP server.
  81. ##
  82. ## If the `smtp` object was created with `debug` enabled,
  83. ## debugRecv will invoke `echo("S:" & result.string)` after
  84. ## the data is received.
  85. ##
  86. ## This is a lower level proc and not something that you typically
  87. ## would need to call when using this module. One exception to
  88. ## this is if you are implementing any
  89. ## `SMTP extensions<https://en.wikipedia.org/wiki/Extended_SMTP>`_.
  90. ##
  91. ## See `checkReply(reply)<#checkReply,AsyncSmtp,string>`_.
  92. result = await smtp.sock.recvLine()
  93. if smtp.debug:
  94. echo("S:" & result)
  95. proc quitExcpt(smtp: Smtp, msg: string) =
  96. smtp.debugSend("QUIT")
  97. raise newException(ReplyError, msg)
  98. const compiledWithSsl = defined(ssl)
  99. when not defined(ssl):
  100. let defaultSSLContext: SslContext = nil
  101. else:
  102. var defaultSSLContext {.threadvar.}: SslContext
  103. proc getSSLContext(): SslContext =
  104. if defaultSSLContext == nil:
  105. defaultSSLContext = newContext(verifyMode = CVerifyNone)
  106. result = defaultSSLContext
  107. proc createMessage*(mSubject, mBody: string, mTo, mCc: seq[string],
  108. otherHeaders: openArray[tuple[name, value: string]]): Message =
  109. ## Creates a new MIME compliant message.
  110. ##
  111. ## You need to make sure that `mSubject`, `mTo` and `mCc` don't contain
  112. ## any newline characters. Failing to do so will raise `AssertionDefect`.
  113. doAssert(not mSubject.contains({'\c', '\L'}),
  114. "'mSubject' shouldn't contain any newline characters")
  115. doAssert(not (mTo.containsNewline() or mCc.containsNewline()),
  116. "'mTo' and 'mCc' shouldn't contain any newline characters")
  117. result.msgTo = mTo
  118. result.msgCc = mCc
  119. result.msgSubject = mSubject
  120. result.msgBody = mBody
  121. result.msgOtherHeaders = newStringTable()
  122. for n, v in items(otherHeaders):
  123. result.msgOtherHeaders[n] = v
  124. proc createMessage*(mSubject, mBody: string, mTo,
  125. mCc: seq[string] = @[]): Message =
  126. ## Alternate version of the above.
  127. ##
  128. ## You need to make sure that `mSubject`, `mTo` and `mCc` don't contain
  129. ## any newline characters. Failing to do so will raise `AssertionDefect`.
  130. doAssert(not mSubject.contains({'\c', '\L'}),
  131. "'mSubject' shouldn't contain any newline characters")
  132. doAssert(not (mTo.containsNewline() or mCc.containsNewline()),
  133. "'mTo' and 'mCc' shouldn't contain any newline characters")
  134. result.msgTo = mTo
  135. result.msgCc = mCc
  136. result.msgSubject = mSubject
  137. result.msgBody = mBody
  138. result.msgOtherHeaders = newStringTable()
  139. proc `$`*(msg: Message): string =
  140. ## stringify for `Message`.
  141. result = ""
  142. if msg.msgTo.len() > 0:
  143. result = "TO: " & msg.msgTo.join(", ") & "\c\L"
  144. if msg.msgCc.len() > 0:
  145. result.add("CC: " & msg.msgCc.join(", ") & "\c\L")
  146. # TODO: Folding? i.e when a line is too long, shorten it...
  147. result.add("Subject: " & msg.msgSubject & "\c\L")
  148. for key, value in pairs(msg.msgOtherHeaders):
  149. result.add(key & ": " & value & "\c\L")
  150. result.add("\c\L")
  151. result.add(msg.msgBody)
  152. proc newSmtp*(useSsl = false, debug = false, sslContext: SslContext = nil): Smtp =
  153. ## Creates a new `Smtp` instance.
  154. new result
  155. result.debug = debug
  156. result.sock = newSocket()
  157. if useSsl:
  158. when compiledWithSsl:
  159. if sslContext == nil:
  160. getSSLContext().wrapSocket(result.sock)
  161. else:
  162. sslContext.wrapSocket(result.sock)
  163. else:
  164. {.error: "SMTP module compiled without SSL support".}
  165. proc newAsyncSmtp*(useSsl = false, debug = false, sslContext: SslContext = nil): AsyncSmtp =
  166. ## Creates a new `AsyncSmtp` instance.
  167. new result
  168. result.debug = debug
  169. result.sock = newAsyncSocket()
  170. if useSsl:
  171. when compiledWithSsl:
  172. if sslContext == nil:
  173. getSSLContext().wrapSocket(result.sock)
  174. else:
  175. sslContext.wrapSocket(result.sock)
  176. else:
  177. {.error: "SMTP module compiled without SSL support".}
  178. proc quitExcpt(smtp: AsyncSmtp, msg: string): Future[void] =
  179. var retFuture = newFuture[void]()
  180. var sendFut = smtp.debugSend("QUIT")
  181. sendFut.callback =
  182. proc () =
  183. retFuture.fail(newException(ReplyError, msg))
  184. return retFuture
  185. proc checkReply*(smtp: Smtp | AsyncSmtp, reply: string) {.multisync.} =
  186. ## Calls `debugRecv<#debugRecv,AsyncSmtp>`_ and checks that the received
  187. ## data starts with `reply`. If the received data does not start
  188. ## with `reply`, then a `QUIT` command will be sent to the SMTP
  189. ## server and a `ReplyError` exception will be raised.
  190. ##
  191. ## This is a lower level proc and not something that you typically
  192. ## would need to call when using this module. One exception to
  193. ## this is if you are implementing any
  194. ## `SMTP extensions<https://en.wikipedia.org/wiki/Extended_SMTP>`_.
  195. var line = await smtp.debugRecv()
  196. if not line.startsWith(reply):
  197. await quitExcpt(smtp, "Expected " & reply & " reply, got: " & line)
  198. proc helo*(smtp: Smtp | AsyncSmtp) {.multisync.} =
  199. # Sends the HELO request
  200. await smtp.debugSend("HELO " & smtp.address & "\c\L")
  201. await smtp.checkReply("250")
  202. proc recvEhlo(smtp: Smtp | AsyncSmtp): Future[bool] {.multisync.} =
  203. ## Skips "250-" lines, read until "250 " found.
  204. ## Return `true` if server supports `EHLO`, false otherwise.
  205. while true:
  206. var line = await smtp.sock.recvLine()
  207. if smtp.debug:
  208. echo("S:" & line)
  209. if line.startsWith("250-"): continue
  210. elif line.startsWith("250 "): return true # last line
  211. else: return false
  212. proc ehlo*(smtp: Smtp | AsyncSmtp): Future[bool] {.multisync.} =
  213. ## Sends EHLO request.
  214. await smtp.debugSend("EHLO " & smtp.address & "\c\L")
  215. return await smtp.recvEhlo()
  216. proc connect*(smtp: Smtp | AsyncSmtp,
  217. address: string, port: Port) {.multisync.} =
  218. ## Establishes a connection with a SMTP server.
  219. ## May fail with ReplyError or with a socket error.
  220. smtp.address = address
  221. await smtp.sock.connect(address, port)
  222. await smtp.checkReply("220")
  223. let speaksEsmtp = await smtp.ehlo()
  224. if not speaksEsmtp:
  225. await smtp.helo()
  226. proc startTls*(smtp: Smtp | AsyncSmtp, sslContext: SslContext = nil) {.multisync.} =
  227. ## Put the SMTP connection in TLS (Transport Layer Security) mode.
  228. ## May fail with ReplyError
  229. await smtp.debugSend("STARTTLS\c\L")
  230. await smtp.checkReply("220")
  231. when compiledWithSsl:
  232. if sslContext == nil:
  233. getSSLContext().wrapConnectedSocket(smtp.sock, handshakeAsClient)
  234. else:
  235. sslContext.wrapConnectedSocket(smtp.sock, handshakeAsClient)
  236. let speaksEsmtp = await smtp.ehlo()
  237. if not speaksEsmtp:
  238. await smtp.helo()
  239. else:
  240. {.error: "SMTP module compiled without SSL support".}
  241. proc auth*(smtp: Smtp | AsyncSmtp, username, password: string) {.multisync.} =
  242. ## Sends an AUTH command to the server to login as the `username`
  243. ## using `password`.
  244. ## May fail with ReplyError.
  245. await smtp.debugSend("AUTH LOGIN\c\L")
  246. await smtp.checkReply("334") # TODO: Check whether it's asking for the "Username:"
  247. # i.e "334 VXNlcm5hbWU6"
  248. await smtp.debugSend(encode(username) & "\c\L")
  249. await smtp.checkReply("334") # TODO: Same as above, only "Password:" (I think?)
  250. await smtp.debugSend(encode(password) & "\c\L")
  251. await smtp.checkReply("235") # Check whether the authentication was successful.
  252. proc sendMail*(smtp: Smtp | AsyncSmtp, fromAddr: string,
  253. toAddrs: seq[string], msg: string) {.multisync.} =
  254. ## Sends `msg` from `fromAddr` to the addresses specified in `toAddrs`.
  255. ## Messages may be formed using `createMessage` by converting the
  256. ## Message into a string.
  257. ##
  258. ## You need to make sure that `fromAddr` and `toAddrs` don't contain
  259. ## any newline characters. Failing to do so will raise `AssertionDefect`.
  260. doAssert(not (toAddrs.containsNewline() or fromAddr.contains({'\c', '\L'})),
  261. "'toAddrs' and 'fromAddr' shouldn't contain any newline characters")
  262. await smtp.debugSend("MAIL FROM:<" & fromAddr & ">\c\L")
  263. await smtp.checkReply("250")
  264. for address in items(toAddrs):
  265. await smtp.debugSend("RCPT TO:<" & address & ">\c\L")
  266. await smtp.checkReply("250")
  267. # Send the message
  268. await smtp.debugSend("DATA " & "\c\L")
  269. await smtp.checkReply("354")
  270. await smtp.sock.send(msg & "\c\L")
  271. await smtp.debugSend(".\c\L")
  272. await smtp.checkReply("250")
  273. proc close*(smtp: Smtp | AsyncSmtp) {.multisync.} =
  274. ## Disconnects from the SMTP server and closes the socket.
  275. await smtp.debugSend("QUIT\c\L")
  276. smtp.sock.close()
  277. when not defined(testing) and isMainModule:
  278. # To test with a real SMTP service, create a smtp.ini file, e.g.:
  279. # username = ""
  280. # password = ""
  281. # smtphost = "smtp.gmail.com"
  282. # port = 465
  283. # use_tls = true
  284. # sender = ""
  285. # recipient = ""
  286. import parsecfg
  287. proc `[]`(c: Config, key: string): string = c.getSectionValue("", key)
  288. let
  289. conf = loadConfig("smtp.ini")
  290. msg = createMessage("Hello from Nim's SMTP!",
  291. "Hello!\n Is this awesome or what?", @[conf["recipient"]])
  292. assert conf["smtphost"] != ""
  293. proc async_test() {.async.} =
  294. let client = newAsyncSmtp(
  295. conf["use_tls"].parseBool,
  296. debug = true
  297. )
  298. await client.connect(conf["smtphost"], conf["port"].parseInt.Port)
  299. await client.auth(conf["username"], conf["password"])
  300. await client.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  301. await client.close()
  302. echo "async email sent"
  303. proc sync_test() =
  304. var smtpConn = newSmtp(
  305. conf["use_tls"].parseBool,
  306. debug = true
  307. )
  308. smtpConn.connect(conf["smtphost"], conf["port"].parseInt.Port)
  309. smtpConn.auth(conf["username"], conf["password"])
  310. smtpConn.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  311. smtpConn.close()
  312. echo "sync email sent"
  313. waitFor async_test()
  314. sync_test()