smtp.nim 8.6 KB

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