高热共公日志库
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.

150 lines
3.7 KiB

  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package logs
  15. import (
  16. "crypto/tls"
  17. "encoding/json"
  18. "fmt"
  19. "net"
  20. "net/smtp"
  21. "strings"
  22. "time"
  23. )
  24. // SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server.
  25. type SMTPWriter struct {
  26. Username string `json:"username"`
  27. Password string `json:"password"`
  28. Host string `json:"host"`
  29. Subject string `json:"subject"`
  30. FromAddress string `json:"fromAddress"`
  31. RecipientAddresses []string `json:"sendTos"`
  32. Level int `json:"level"`
  33. }
  34. // NewSMTPWriter create smtp writer.
  35. func newSMTPWriter() Logger {
  36. return &SMTPWriter{Level: LevelTrace}
  37. }
  38. // Init smtp writer with json config.
  39. // config like:
  40. // {
  41. // "username":"example@gmail.com",
  42. // "password:"password",
  43. // "host":"smtp.gmail.com:465",
  44. // "subject":"email title",
  45. // "fromAddress":"from@example.com",
  46. // "sendTos":["email1","email2"],
  47. // "level":LevelError
  48. // }
  49. func (s *SMTPWriter) Init(jsonconfig string) error {
  50. return json.Unmarshal([]byte(jsonconfig), s)
  51. }
  52. func (s *SMTPWriter) getSMTPAuth(host string) smtp.Auth {
  53. if len(strings.Trim(s.Username, " ")) == 0 && len(strings.Trim(s.Password, " ")) == 0 {
  54. return nil
  55. }
  56. return smtp.PlainAuth(
  57. "",
  58. s.Username,
  59. s.Password,
  60. host,
  61. )
  62. }
  63. func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error {
  64. client, err := smtp.Dial(hostAddressWithPort)
  65. if err != nil {
  66. return err
  67. }
  68. host, _, _ := net.SplitHostPort(hostAddressWithPort)
  69. tlsConn := &tls.Config{
  70. InsecureSkipVerify: true,
  71. ServerName: host,
  72. }
  73. if err = client.StartTLS(tlsConn); err != nil {
  74. return err
  75. }
  76. if auth != nil {
  77. if err = client.Auth(auth); err != nil {
  78. return err
  79. }
  80. }
  81. if err = client.Mail(fromAddress); err != nil {
  82. return err
  83. }
  84. for _, rec := range recipients {
  85. if err = client.Rcpt(rec); err != nil {
  86. return err
  87. }
  88. }
  89. w, err := client.Data()
  90. if err != nil {
  91. return err
  92. }
  93. _, err = w.Write(msgContent)
  94. if err != nil {
  95. return err
  96. }
  97. err = w.Close()
  98. if err != nil {
  99. return err
  100. }
  101. return client.Quit()
  102. }
  103. // WriteMsg write message in smtp writer.
  104. // it will send an email with subject and only this message.
  105. func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error {
  106. if level > s.Level {
  107. return nil
  108. }
  109. hp := strings.Split(s.Host, ":")
  110. // Set up authentication information.
  111. auth := s.getSMTPAuth(hp[0])
  112. // Connect to the server, authenticate, set the sender and recipient,
  113. // and send the email all in one step.
  114. contentType := "Content-Type: text/plain" + "; charset=UTF-8"
  115. mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
  116. ">\r\nSubject: " + s.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", when.Format("2006-01-02 15:04:05")) + msg)
  117. return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
  118. }
  119. // Flush implementing method. empty.
  120. func (s *SMTPWriter) Flush() {
  121. }
  122. // Destroy implementing method. empty.
  123. func (s *SMTPWriter) Destroy() {
  124. }
  125. func init() {
  126. Register(AdapterMail, newSMTPWriter)
  127. }