smtp.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package log
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/smtp"
  9. "strings"
  10. "time"
  11. )
  12. const (
  13. subjectPhrase = "Diagnostic message from server"
  14. )
  15. // smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
  16. type SmtpWriter struct {
  17. Username string `json:"Username"`
  18. Password string `json:"password"`
  19. Host string `json:"Host"`
  20. Subject string `json:"subject"`
  21. RecipientAddresses []string `json:"sendTos"`
  22. Level int `json:"level"`
  23. }
  24. // create smtp writer.
  25. func NewSmtpWriter() LoggerInterface {
  26. return &SmtpWriter{Level: TRACE}
  27. }
  28. // init smtp writer with json config.
  29. // config like:
  30. // {
  31. // "Username":"example@gmail.com",
  32. // "password:"password",
  33. // "host":"smtp.gmail.com:465",
  34. // "subject":"email title",
  35. // "sendTos":["email1","email2"],
  36. // "level":LevelError
  37. // }
  38. func (sw *SmtpWriter) Init(jsonconfig string) error {
  39. return json.Unmarshal([]byte(jsonconfig), sw)
  40. }
  41. // write message in smtp writer.
  42. // it will send an email with subject and only this message.
  43. func (s *SmtpWriter) WriteMsg(msg string, skip, level int) error {
  44. if level < s.Level {
  45. return nil
  46. }
  47. hp := strings.Split(s.Host, ":")
  48. // Set up authentication information.
  49. auth := smtp.PlainAuth(
  50. "",
  51. s.Username,
  52. s.Password,
  53. hp[0],
  54. )
  55. // Connect to the server, authenticate, set the sender and recipient,
  56. // and send the email all in one step.
  57. content_type := "Content-Type: text/plain" + "; charset=UTF-8"
  58. mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username +
  59. ">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
  60. return smtp.SendMail(
  61. s.Host,
  62. auth,
  63. s.Username,
  64. s.RecipientAddresses,
  65. mailmsg,
  66. )
  67. }
  68. func (_ *SmtpWriter) Flush() {
  69. }
  70. func (_ *SmtpWriter) Destroy() {
  71. }
  72. func init() {
  73. Register("smtp", NewSmtpWriter)
  74. }