smtp.nim 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. ## For SSL support this module relies on OpenSSL. If you want to
  29. ## enable SSL, compile with ``-d:ssl``.
  30. import net, strutils, strtabs, base64, os
  31. import asyncnet, asyncdispatch
  32. export Port
  33. type
  34. Message* = object
  35. msgTo: seq[string]
  36. msgCc: seq[string]
  37. msgSubject: string
  38. msgOtherHeaders: StringTableRef
  39. msgBody: string
  40. ReplyError* = object of IOError
  41. SmtpBase[SocketType] = ref object
  42. sock: SocketType
  43. debug: bool
  44. Smtp* = SmtpBase[Socket]
  45. AsyncSmtp* = SmtpBase[AsyncSocket]
  46. proc debugSend(smtp: Smtp | AsyncSmtp, cmd: string) {.multisync.} =
  47. if smtp.debug:
  48. echo("C:" & cmd)
  49. await smtp.sock.send(cmd)
  50. proc debugRecv(smtp: Smtp | AsyncSmtp): Future[TaintedString] {.multisync.} =
  51. result = await smtp.sock.recvLine()
  52. if smtp.debug:
  53. echo("S:" & result.string)
  54. proc quitExcpt(smtp: Smtp, msg: string) =
  55. smtp.debugSend("QUIT")
  56. raise newException(ReplyError, msg)
  57. const compiledWithSsl = defined(ssl)
  58. when not defined(ssl):
  59. type PSSLContext = ref object
  60. let defaultSSLContext: PSSLContext = nil
  61. else:
  62. var defaultSSLContext {.threadvar.}: SSLContext
  63. proc getSSLContext(): SSLContext =
  64. if defaultSSLContext == nil:
  65. defaultSSLContext = newContext(verifyMode = CVerifyNone)
  66. result = defaultSSLContext
  67. proc createMessage*(mSubject, mBody: string, mTo, mCc: seq[string],
  68. otherHeaders: openarray[tuple[name, value: string]]): Message =
  69. ## Creates a new MIME compliant message.
  70. result.msgTo = mTo
  71. result.msgCc = mCc
  72. result.msgSubject = mSubject
  73. result.msgBody = mBody
  74. result.msgOtherHeaders = newStringTable()
  75. for n, v in items(otherHeaders):
  76. result.msgOtherHeaders[n] = v
  77. proc createMessage*(mSubject, mBody: string, mTo,
  78. mCc: seq[string] = @[]): Message =
  79. ## Alternate version of the above.
  80. result.msgTo = mTo
  81. result.msgCc = mCc
  82. result.msgSubject = mSubject
  83. result.msgBody = mBody
  84. result.msgOtherHeaders = newStringTable()
  85. proc `$`*(msg: Message): string =
  86. ## stringify for ``Message``.
  87. result = ""
  88. if msg.msgTo.len() > 0:
  89. result = "TO: " & msg.msgTo.join(", ") & "\c\L"
  90. if msg.msgCc.len() > 0:
  91. result.add("CC: " & msg.msgCc.join(", ") & "\c\L")
  92. # TODO: Folding? i.e when a line is too long, shorten it...
  93. result.add("Subject: " & msg.msgSubject & "\c\L")
  94. for key, value in pairs(msg.msgOtherHeaders):
  95. result.add(key & ": " & value & "\c\L")
  96. result.add("\c\L")
  97. result.add(msg.msgBody)
  98. proc newSmtp*(useSsl = false, debug=false,
  99. sslContext: SSLContext = nil): Smtp =
  100. ## Creates a new ``Smtp`` instance.
  101. new result
  102. result.debug = debug
  103. result.sock = newSocket()
  104. if useSsl:
  105. when compiledWithSsl:
  106. if sslContext == nil:
  107. getSSLContext().wrapSocket(result.sock)
  108. else:
  109. sslContext.wrapSocket(result.sock)
  110. else:
  111. {.error: "SMTP module compiled without SSL support".}
  112. proc newAsyncSmtp*(useSsl = false, debug=false,
  113. sslContext: SSLContext = nil): AsyncSmtp =
  114. ## Creates a new ``AsyncSmtp`` instance.
  115. new result
  116. result.debug = debug
  117. result.sock = newAsyncSocket()
  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 quitExcpt(smtp: AsyncSmtp, msg: string): Future[void] =
  127. var retFuture = newFuture[void]()
  128. var sendFut = smtp.debugSend("QUIT")
  129. sendFut.callback =
  130. proc () =
  131. # TODO: Fix this in async procs.
  132. raise newException(ReplyError, msg)
  133. return retFuture
  134. proc checkReply(smtp: Smtp | AsyncSmtp, reply: string) {.multisync.} =
  135. var line = await smtp.debugRecv()
  136. if not line.startswith(reply):
  137. await quitExcpt(smtp, "Expected " & reply & " reply, got: " & line)
  138. proc connect*(smtp: Smtp | AsyncSmtp,
  139. address: string, port: Port) {.multisync.} =
  140. ## Establishes a connection with a SMTP server.
  141. ## May fail with ReplyError or with a socket error.
  142. await smtp.sock.connect(address, port)
  143. await smtp.checkReply("220")
  144. await smtp.debugSend("HELO " & address & "\c\L")
  145. await smtp.checkReply("250")
  146. proc auth*(smtp: Smtp | AsyncSmtp, username, password: string) {.multisync.} =
  147. ## Sends an AUTH command to the server to login as the `username`
  148. ## using `password`.
  149. ## May fail with ReplyError.
  150. await smtp.debugSend("AUTH LOGIN\c\L")
  151. await smtp.checkReply("334") # TODO: Check whether it's asking for the "Username:"
  152. # i.e "334 VXNlcm5hbWU6"
  153. await smtp.debugSend(encode(username) & "\c\L")
  154. await smtp.checkReply("334") # TODO: Same as above, only "Password:" (I think?)
  155. await smtp.debugSend(encode(password) & "\c\L")
  156. await smtp.checkReply("235") # Check whether the authentification was successful.
  157. proc sendMail*(smtp: Smtp | AsyncSmtp, fromAddr: string,
  158. toAddrs: seq[string], msg: string) {.multisync.} =
  159. ## Sends ``msg`` from ``fromAddr`` to the addresses specified in ``toAddrs``.
  160. ## Messages may be formed using ``createMessage`` by converting the
  161. ## Message into a string.
  162. await smtp.debugSend("MAIL FROM:<" & fromAddr & ">\c\L")
  163. await smtp.checkReply("250")
  164. for address in items(toAddrs):
  165. await smtp.debugSend("RCPT TO:<" & address & ">\c\L")
  166. await smtp.checkReply("250")
  167. # Send the message
  168. await smtp.debugSend("DATA " & "\c\L")
  169. await smtp.checkReply("354")
  170. await smtp.sock.send(msg & "\c\L")
  171. await smtp.debugSend(".\c\L")
  172. await smtp.checkReply("250")
  173. proc close*(smtp: Smtp | AsyncSmtp) {.multisync.} =
  174. ## Disconnects from the SMTP server and closes the socket.
  175. await smtp.debugSend("QUIT\c\L")
  176. smtp.sock.close()
  177. when not defined(testing) and isMainModule:
  178. # To test with a real SMTP service, create a smtp.ini file, e.g.:
  179. # username = ""
  180. # password = ""
  181. # smtphost = "smtp.gmail.com"
  182. # port = 465
  183. # use_tls = true
  184. # sender = ""
  185. # recipient = ""
  186. import parsecfg
  187. proc `[]`(c: Config, key: string): string = c.getSectionValue("", key)
  188. let
  189. conf = loadConfig("smtp.ini")
  190. msg = createMessage("Hello from Nim's SMTP!",
  191. "Hello!\n Is this awesome or what?", @[conf["recipient"]])
  192. assert conf["smtphost"] != ""
  193. proc async_test() {.async.} =
  194. let client = newAsyncSmtp(
  195. conf["use_tls"].parseBool,
  196. debug=true
  197. )
  198. await client.connect(conf["smtphost"], conf["port"].parseInt.Port)
  199. await client.auth(conf["username"], conf["password"])
  200. await client.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  201. await client.close()
  202. echo "async email sent"
  203. proc sync_test() =
  204. var smtpConn = newSmtp(
  205. conf["use_tls"].parseBool,
  206. debug=true
  207. )
  208. smtpConn.connect(conf["smtphost"], conf["port"].parseInt.Port)
  209. smtpConn.auth(conf["username"], conf["password"])
  210. smtpConn.sendMail(conf["sender"], @[conf["recipient"]], $msg)
  211. smtpConn.close()
  212. echo "sync email sent"
  213. waitFor async_test()
  214. sync_test()