smtp.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. debug: bool
  58. Smtp* = SmtpBase[Socket]
  59. AsyncSmtp* = SmtpBase[AsyncSocket]
  60. proc containsNewline(xs: seq[string]): bool =
  61. for x in xs:
  62. if x.contains({'\c', '\L'}):
  63. return true
  64. proc debugSend*(smtp: Smtp | AsyncSmtp, cmd: string) {.multisync.} =
  65. ## Sends ``cmd`` on the socket connected to the SMTP server.
  66. ##
  67. ## If the ``smtp`` object was created with ``debug`` enabled,
  68. ## debugSend will invoke ``echo("C:" & cmd)`` before sending.
  69. ##
  70. ## This is a lower level proc and not something that you typically
  71. ## would need to call when using this module. One exception to
  72. ## this is if you are implementing any
  73. ## `SMTP extensions<https://en.wikipedia.org/wiki/Extended_SMTP>`_.
  74. if smtp.debug:
  75. echo("C:" & cmd)
  76. await smtp.sock.send(cmd)
  77. proc debugRecv(smtp: Smtp | AsyncSmtp): Future[TaintedString] {.multisync.} =
  78. result = await smtp.sock.recvLine()
  79. if smtp.debug:
  80. echo("S:" & result.string)
  81. proc quitExcpt(smtp: Smtp, msg: string) =
  82. smtp.debugSend("QUIT")
  83. raise newException(ReplyError, msg)
  84. const compiledWithSsl = defined(ssl)
  85. when not defined(ssl):
  86. type PSSLContext = ref object
  87. let defaultSSLContext: PSSLContext = nil
  88. else:
  89. var defaultSSLContext {.threadvar.}: SSLContext
  90. proc getSSLContext(): SSLContext =
  91. if defaultSSLContext == nil:
  92. defaultSSLContext = newContext(verifyMode = CVerifyNone)
  93. result = defaultSSLContext
  94. proc createMessage*(mSubject, mBody: string, mTo, mCc: seq[string],
  95. otherHeaders: openarray[tuple[name, value: string]]): Message =
  96. ## Creates a new MIME compliant message.
  97. ##
  98. ## You need to make sure that ``mSubject``, ``mTo`` and ``mCc`` don't contain
  99. ## any newline characters. Failing to do so will raise ``AssertionDefect``.
  100. doAssert(not mSubject.contains({'\c', '\L'}),
  101. "'mSubject' shouldn't contain any newline characters")
  102. doAssert(not (mTo.containsNewline() or mCc.containsNewline()),
  103. "'mTo' and 'mCc' shouldn't contain any newline characters")
  104. result.msgTo = mTo
  105. result.msgCc = mCc
  106. result.msgSubject = mSubject
  107. result.msgBody = mBody
  108. result.msgOtherHeaders = newStringTable()
  109. for n, v in items(otherHeaders):
  110. result.msgOtherHeaders[n] = v
  111. proc createMessage*(mSubject, mBody: string, mTo,
  112. mCc: seq[string] = @[]): Message =
  113. ## Alternate version of the above.
  114. ##
  115. ## You need to make sure that ``mSubject``, ``mTo`` and ``mCc`` don't contain
  116. ## any newline characters. Failing to do so will raise ``AssertionDefect``.
  117. doAssert(not mSubject.contains({'\c', '\L'}),
  118. "'mSubject' shouldn't contain any newline characters")
  119. doAssert(not (mTo.containsNewline() or mCc.containsNewline()),
  120. "'mTo' and 'mCc' shouldn't contain any newline characters")
  121. result.msgTo = mTo
  122. result.msgCc = mCc
  123. result.msgSubject = mSubject
  124. result.msgBody = mBody
  125. result.msgOtherHeaders = newStringTable()
  126. proc `$`*(msg: Message): string =
  127. ## stringify for ``Message``.
  128. result = ""
  129. if msg.msgTo.len() > 0:
  130. result = "TO: " & msg.msgTo.join(", ") & "\c\L"
  131. if msg.msgCc.len() > 0:
  132. result.add("CC: " & msg.msgCc.join(", ") & "\c\L")
  133. # TODO: Folding? i.e when a line is too long, shorten it...
  134. result.add("Subject: " & msg.msgSubject & "\c\L")
  135. for key, value in pairs(msg.msgOtherHeaders):
  136. result.add(key & ": " & value & "\c\L")
  137. result.add("\c\L")
  138. result.add(msg.msgBody)
  139. proc newSmtp*(useSsl = false, debug = false,
  140. sslContext: SSLContext = nil): Smtp =
  141. ## Creates a new ``Smtp`` instance.
  142. new result
  143. result.debug = debug
  144. result.sock = newSocket()
  145. if useSsl:
  146. when compiledWithSsl:
  147. if sslContext == nil:
  148. getSSLContext().wrapSocket(result.sock)
  149. else:
  150. sslContext.wrapSocket(result.sock)
  151. else:
  152. {.error: "SMTP module compiled without SSL support".}
  153. proc newAsyncSmtp*(useSsl = false, debug = false,
  154. sslContext: SSLContext = nil): AsyncSmtp =
  155. ## Creates a new ``AsyncSmtp`` instance.
  156. new result
  157. result.debug = debug
  158. result.sock = newAsyncSocket()
  159. if useSsl:
  160. when compiledWithSsl:
  161. if sslContext == nil:
  162. getSSLContext().wrapSocket(result.sock)
  163. else:
  164. sslContext.wrapSocket(result.sock)
  165. else:
  166. {.error: "SMTP module compiled without SSL support".}
  167. proc quitExcpt(smtp: AsyncSmtp, msg: string): Future[void] =
  168. var retFuture = newFuture[void]()
  169. var sendFut = smtp.debugSend("QUIT")
  170. sendFut.callback =
  171. proc () =
  172. retFuture.fail(newException(ReplyError, msg))
  173. return retFuture
  174. proc checkReply(smtp: Smtp | AsyncSmtp, reply: string) {.multisync.} =
  175. var line = await smtp.debugRecv()
  176. if not line.startswith(reply):
  177. await quitExcpt(smtp, "Expected " & reply & " reply, got: " & line)
  178. proc connect*(smtp: Smtp | AsyncSmtp,
  179. address: string, port: Port) {.multisync.} =
  180. ## Establishes a connection with a SMTP server.
  181. ## May fail with ReplyError or with a socket error.
  182. await smtp.sock.connect(address, port)
  183. await smtp.checkReply("220")
  184. await smtp.debugSend("HELO " & address & "\c\L")
  185. await smtp.checkReply("250")
  186. proc startTls*(smtp: Smtp | AsyncSmtp, sslContext: SSLContext = nil) {.multisync.} =
  187. ## Put the SMTP connection in TLS (Transport Layer Security) mode.
  188. ## May fail with ReplyError
  189. await smtp.debugSend("STARTTLS\c\L")
  190. await smtp.checkReply("220")
  191. when compiledWithSsl:
  192. if sslContext == nil:
  193. getSSLContext().wrapConnectedSocket(smtp.sock, handshakeAsClient)
  194. else:
  195. sslContext.wrapConnectedSocket(smtp.sock, handshakeAsClient)
  196. else:
  197. {.error: "SMTP module compiled without SSL support".}
  198. proc auth*(smtp: Smtp | AsyncSmtp, username, password: string) {.multisync.} =
  199. ## Sends an AUTH command to the server to login as the `username`
  200. ## using `password`.
  201. ## May fail with ReplyError.
  202. await smtp.debugSend("AUTH LOGIN\c\L")
  203. await smtp.checkReply("334") # TODO: Check whether it's asking for the "Username:"
  204. # i.e "334 VXNlcm5hbWU6"
  205. await smtp.debugSend(encode(username) & "\c\L")
  206. await smtp.checkReply("334") # TODO: Same as above, only "Password:" (I think?)
  207. await smtp.debugSend(encode(password) & "\c\L")
  208. await smtp.checkReply("235") # Check whether the authentication was successful.
  209. proc sendMail*(smtp: Smtp | AsyncSmtp, fromAddr: string,
  210. toAddrs: seq[string], msg: string) {.multisync.} =
  211. ## Sends ``msg`` from ``fromAddr`` to the addresses specified in ``toAddrs``.
  212. ## Messages may be formed using ``createMessage`` by converting the
  213. ## Message into a string.
  214. ##
  215. ## You need to make sure that ``fromAddr`` and ``toAddrs`` don't contain
  216. ## any newline characters. Failing to do so will raise ``AssertionDefect``.
  217. doAssert(not (toAddrs.containsNewline() or fromAddr.contains({'\c', '\L'})),
  218. "'toAddrs' and 'fromAddr' shouldn't contain any newline characters")
  219. await smtp.debugSend("MAIL FROM:<" & fromAddr & ">\c\L")
  220. await smtp.checkReply("250")
  221. for address in items(toAddrs):
  222. await smtp.debugSend("RCPT TO:<" & address & ">\c\L")
  223. await smtp.checkReply("250")
  224. # Send the message
  225. await smtp.debugSend("DATA " & "\c\L")
  226. await smtp.checkReply("354")
  227. await smtp.sock.send(msg & "\c\L")
  228. await smtp.debugSend(".\c\L")
  229. await smtp.checkReply("250")
  230. proc close*(smtp: Smtp | AsyncSmtp) {.multisync.} =
  231. ## Disconnects from the SMTP server and closes the socket.
  232. await smtp.debugSend("QUIT\c\L")
  233. smtp.sock.close()
  234. when not defined(testing) and isMainModule:
  235. # To test with a real SMTP service, create a smtp.ini file, e.g.:
  236. # username = ""
  237. # password = ""
  238. # smtphost = "smtp.gmail.com"
  239. # port = 465
  240. # use_tls = true
  241. # sender = ""
  242. # recipient = ""
  243. import parsecfg
  244. proc `[]`(c: Config, key: string): string = c.getSectionValue("", key)
  245. let
  246. conf = loadConfig("smtp.ini")
  247. msg = createMessage("Hello from Nim's SMTP!",
  248. "Hello!\n Is this awesome or what?", @[conf["recipient"]])
  249. assert conf["smtphost"] != ""
  250. proc async_test() {.async.} =
  251. let client = newAsyncSmtp(
  252. conf["use_tls"].parseBool,
  253. debug = true
  254. )
  255. await client.connect(conf["smtphost"], conf["port"].parseInt.Port)
  256. await client.auth(conf["username"], conf["password"])
  257. await client.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  258. await client.close()
  259. echo "async email sent"
  260. proc sync_test() =
  261. var smtpConn = newSmtp(
  262. conf["use_tls"].parseBool,
  263. debug = true
  264. )
  265. smtpConn.connect(conf["smtphost"], conf["port"].parseInt.Port)
  266. smtpConn.auth(conf["username"], conf["password"])
  267. smtpConn.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  268. smtpConn.close()
  269. echo "sync email sent"
  270. waitFor async_test()
  271. sync_test()