smtpn.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package smtpn
  2. /*
  3. SMTP Notifaiction Agent
  4. This is the mail sending agent for sending notification to user
  5. */
  6. import (
  7. "io/ioutil"
  8. "log"
  9. "net/smtp"
  10. "strconv"
  11. "time"
  12. "github.com/valyala/fasttemplate"
  13. notification "imuslab.com/arozos/mod/notification"
  14. )
  15. type Agent struct {
  16. Hostname string
  17. SMTPSenderDisplayName string
  18. SMTPSender string
  19. SMTPPassword string
  20. SMTPDomain string
  21. SMTPPort int
  22. UsernameToEmailMap map[string]string
  23. }
  24. func (a Agent) Name() string {
  25. return "smtpn"
  26. }
  27. func (a Agent) Desc() string {
  28. return "Notify user throught email"
  29. }
  30. func (a Agent) IsConsumer() bool {
  31. return true
  32. }
  33. func (a Agent) IsProducer() bool {
  34. return false
  35. }
  36. func (a Agent) ConsumerNotification(incomingNotification *notification.NotificationPayload) error {
  37. //Get a notification and send it out
  38. //Analysis the notification, get the target user's email
  39. userEmails := [][]string{}
  40. for _, username := range incomingNotification.Receiver {
  41. userEmail, ok := a.UsernameToEmailMap[username]
  42. if ok {
  43. userEmails = append(userEmails, []string{username, userEmail})
  44. } else {
  45. log.Println("[SMTP Notification] Unable to notify " + username + ": Email not set")
  46. }
  47. }
  48. //For each user, send out the email
  49. for _, thisEntry := range userEmails {
  50. thisUser := thisEntry[0]
  51. thisEmail := thisEntry[1]
  52. //Load email template
  53. template, _ := ioutil.ReadFile("system/www/smtpn.html")
  54. t := fasttemplate.New(string(template), "{{", "}}")
  55. s := t.ExecuteString(map[string]interface{}{
  56. "receiver": "Hello " + thisUser + ",",
  57. "message": incomingNotification.Message,
  58. "sender": incomingNotification.Sender,
  59. "hostname": a.Hostname,
  60. "timestamp": time.Now().Format("2006-01-02 3:4:5 PM"),
  61. })
  62. msg := []byte("To: " + thisEmail + "\n" +
  63. "From: " + a.SMTPSenderDisplayName + " <" + a.SMTPSender + ">\n" +
  64. "Subject: " + incomingNotification.Title + "\n" +
  65. "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" +
  66. s + "\n\n")
  67. //Login to the SMTP server
  68. auth := smtp.PlainAuth("", a.SMTPSender, a.SMTPPassword, a.SMTPDomain)
  69. err := smtp.SendMail(a.SMTPDomain+":"+strconv.Itoa(a.SMTPPort), auth, a.SMTPSender, []string{thisEmail}, msg)
  70. if err != nil {
  71. log.Println("[SMTPN] Email sent failed: ", err.Error())
  72. return err
  73. }
  74. }
  75. return nil
  76. }
  77. func (a Agent) ProduceNotification(producerListeningEndpoint *notification.AgentProducerFunction) {
  78. return
  79. }