smtp.nim 7.4 KB

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