smtp.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. const (
  25. // no usage
  26. // subjectPhrase = "Diagnostic message from server"
  27. )
  28. // smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
  29. type SmtpWriter struct {
  30. Username string `json:"Username"`
  31. Password string `json:"password"`
  32. Host string `json:"Host"`
  33. Subject string `json:"subject"`
  34. FromAddress string `json:"fromAddress"`
  35. RecipientAddresses []string `json:"sendTos"`
  36. Level int `json:"level"`
  37. }
  38. // create smtp writer.
  39. func NewSmtpWriter() LoggerInterface {
  40. return &SmtpWriter{Level: LevelTrace}
  41. }
  42. // init smtp writer with json config.
  43. // config like:
  44. // {
  45. // "Username":"example@gmail.com",
  46. // "password:"password",
  47. // "host":"smtp.gmail.com:465",
  48. // "subject":"email title",
  49. // "fromAddress":"from@example.com",
  50. // "sendTos":["email1","email2"],
  51. // "level":LevelError
  52. // }
  53. func (s *SmtpWriter) Init(jsonconfig string) error {
  54. err := json.Unmarshal([]byte(jsonconfig), s)
  55. if err != nil {
  56. return err
  57. }
  58. return nil
  59. }
  60. func (s *SmtpWriter) GetSmtpAuth(host string) smtp.Auth {
  61. if len(strings.Trim(s.Username, " ")) == 0 && len(strings.Trim(s.Password, " ")) == 0 {
  62. return nil
  63. }
  64. return smtp.PlainAuth(
  65. "",
  66. s.Username,
  67. s.Password,
  68. host,
  69. )
  70. }
  71. func (s *SmtpWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error {
  72. client, err := smtp.Dial(hostAddressWithPort)
  73. if err != nil {
  74. return err
  75. }
  76. host, _, _ := net.SplitHostPort(hostAddressWithPort)
  77. tlsConn := &tls.Config{
  78. InsecureSkipVerify: true,
  79. ServerName: host,
  80. }
  81. if err = client.StartTLS(tlsConn); err != nil {
  82. return err
  83. }
  84. if auth != nil {
  85. if err = client.Auth(auth); err != nil {
  86. return err
  87. }
  88. }
  89. if err = client.Mail(fromAddress); err != nil {
  90. return err
  91. }
  92. for _, rec := range recipients {
  93. if err = client.Rcpt(rec); err != nil {
  94. return err
  95. }
  96. }
  97. w, err := client.Data()
  98. if err != nil {
  99. return err
  100. }
  101. _, err = w.Write([]byte(msgContent))
  102. if err != nil {
  103. return err
  104. }
  105. err = w.Close()
  106. if err != nil {
  107. return err
  108. }
  109. err = client.Quit()
  110. if err != nil {
  111. return err
  112. }
  113. return nil
  114. }
  115. // write message in smtp writer.
  116. // it will send an email with subject and only this message.
  117. func (s *SmtpWriter) WriteMsg(msg string, level int) error {
  118. if level > s.Level {
  119. return nil
  120. }
  121. hp := strings.Split(s.Host, ":")
  122. // Set up authentication information.
  123. auth := s.GetSmtpAuth(hp[0])
  124. // Connect to the server, authenticate, set the sender and recipient,
  125. // and send the email all in one step.
  126. content_type := "Content-Type: text/plain" + "; charset=UTF-8"
  127. mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
  128. ">\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)
  129. return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
  130. }
  131. // implementing method. empty.
  132. func (s *SmtpWriter) Flush() {
  133. return
  134. }
  135. // implementing method. empty.
  136. func (s *SmtpWriter) Destroy() {
  137. return
  138. }
  139. func init() {
  140. Register("smtp", NewSmtpWriter)
  141. }