smtp.nim 7.6 KB

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