1
0

smtp.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. err := json.Unmarshal([]byte(jsonconfig), s)
  51. if err != nil {
  52. return err
  53. }
  54. return nil
  55. }
  56. func (s *SMTPWriter) getSMTPAuth(host string) smtp.Auth {
  57. if len(strings.Trim(s.Username, " ")) == 0 && len(strings.Trim(s.Password, " ")) == 0 {
  58. return nil
  59. }
  60. return smtp.PlainAuth(
  61. "",
  62. s.Username,
  63. s.Password,
  64. host,
  65. )
  66. }
  67. func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error {
  68. client, err := smtp.Dial(hostAddressWithPort)
  69. if err != nil {
  70. return err
  71. }
  72. host, _, _ := net.SplitHostPort(hostAddressWithPort)
  73. tlsConn := &tls.Config{
  74. InsecureSkipVerify: true,
  75. ServerName: host,
  76. }
  77. if err = client.StartTLS(tlsConn); err != nil {
  78. return err
  79. }
  80. if auth != nil {
  81. if err = client.Auth(auth); err != nil {
  82. return err
  83. }
  84. }
  85. if err = client.Mail(fromAddress); err != nil {
  86. return err
  87. }
  88. for _, rec := range recipients {
  89. if err = client.Rcpt(rec); err != nil {
  90. return err
  91. }
  92. }
  93. w, err := client.Data()
  94. if err != nil {
  95. return err
  96. }
  97. _, err = w.Write([]byte(msgContent))
  98. if err != nil {
  99. return err
  100. }
  101. err = w.Close()
  102. if err != nil {
  103. return err
  104. }
  105. err = client.Quit()
  106. if err != nil {
  107. return err
  108. }
  109. return nil
  110. }
  111. // WriteMsg write message in smtp writer.
  112. // it will send an email with subject and only this message.
  113. func (s *SMTPWriter) WriteMsg(when time.Time, msg string, level int) error {
  114. if level > s.Level {
  115. return nil
  116. }
  117. hp := strings.Split(s.Host, ":")
  118. // Set up authentication information.
  119. auth := s.getSMTPAuth(hp[0])
  120. // Connect to the server, authenticate, set the sender and recipient,
  121. // and send the email all in one step.
  122. contentType := "Content-Type: text/plain" + "; charset=UTF-8"
  123. mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
  124. ">\r\nSubject: " + s.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", when.Format("2006-01-02 15:04:05")) + msg)
  125. return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
  126. }
  127. // Flush implementing method. empty.
  128. func (s *SMTPWriter) Flush() {
  129. return
  130. }
  131. // Destroy implementing method. empty.
  132. func (s *SMTPWriter) Destroy() {
  133. return
  134. }
  135. func init() {
  136. Register(AdapterMail, newSMTPWriter)
  137. }