You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.2 KiB

  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. // NewSMTPWriter creates 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. // WriteMsg writes message in smtp writer.
  42. // it will send an email with subject and only this message.
  43. func (sw *SMTPWriter) WriteMsg(msg string, skip, level int) error {
  44. if level < sw.Level {
  45. return nil
  46. }
  47. hp := strings.Split(sw.Host, ":")
  48. // Set up authentication information.
  49. auth := smtp.PlainAuth(
  50. "",
  51. sw.Username,
  52. sw.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. contentType := "Content-Type: text/plain" + "; charset=UTF-8"
  58. mailmsg := []byte("To: " + strings.Join(sw.RecipientAddresses, ";") + "\r\nFrom: " + sw.Username + "<" + sw.Username +
  59. ">\r\nSubject: " + sw.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
  60. return smtp.SendMail(
  61. sw.Host,
  62. auth,
  63. sw.Username,
  64. sw.RecipientAddresses,
  65. mailmsg,
  66. )
  67. }
  68. // Flush when log should be flushed
  69. func (sw *SMTPWriter) Flush() {
  70. }
  71. // Destroy when writer is destroy
  72. func (sw *SMTPWriter) Destroy() {
  73. }
  74. func init() {
  75. Register("smtp", NewSMTPWriter)
  76. }