smtp.go 2.1 KB
Newer Older
A
astaxie 已提交
1 2 3 4
package logs

import (
	"encoding/json"
5
	"fmt"
A
astaxie 已提交
6 7
	"net/smtp"
	"strings"
8
	"time"
A
astaxie 已提交
9 10 11 12 13 14
)

const (
	subjectPhrase = "Diagnostic message from server"
)

F
FuXiaoHei 已提交
15
// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
A
astaxie 已提交
16
type SmtpWriter struct {
1
1fei 已提交
17 18 19 20 21 22
	Username           string   `json:"Username"`
	Password           string   `json:"password"`
	Host               string   `json:"Host"`
	Subject            string   `json:"subject"`
	RecipientAddresses []string `json:"sendTos"`
	Level              int      `json:"level"`
A
astaxie 已提交
23 24
}

F
FuXiaoHei 已提交
25
// create smtp writer.
A
astaxie 已提交
26
func NewSmtpWriter() LoggerInterface {
1
1fei 已提交
27
	return &SmtpWriter{Level: LevelTrace}
A
astaxie 已提交
28 29
}

F
FuXiaoHei 已提交
30 31 32 33 34 35 36 37 38 39
// init smtp writer with json config.
// config like:
//	{
//		"Username":"example@gmail.com",
//		"password:"password",
//		"host":"smtp.gmail.com:465",
//		"subject":"email title",
//		"sendTos":["email1","email2"],
//		"level":LevelError
//	}
A
astaxie 已提交
40
func (s *SmtpWriter) Init(jsonconfig string) error {
1
1fei 已提交
41
	err := json.Unmarshal([]byte(jsonconfig), s)
A
astaxie 已提交
42 43 44 45 46 47
	if err != nil {
		return err
	}
	return nil
}

F
FuXiaoHei 已提交
48 49
// write message in smtp writer.
// it will send an email with subject and only this message.
A
astaxie 已提交
50
func (s *SmtpWriter) WriteMsg(msg string, level int) error {
1
1fei 已提交
51
	if level < s.Level {
A
astaxie 已提交
52 53 54
		return nil
	}

1
1fei 已提交
55
	hp := strings.Split(s.Host, ":")
A
astaxie 已提交
56 57 58 59

	// Set up authentication information.
	auth := smtp.PlainAuth(
		"",
1
1fei 已提交
60 61
		s.Username,
		s.Password,
A
astaxie 已提交
62 63 64 65 66
		hp[0],
	)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	content_type := "Content-Type: text/plain" + "; charset=UTF-8"
1
1fei 已提交
67 68
	mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username +
		">\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)
69

A
astaxie 已提交
70
	err := smtp.SendMail(
1
1fei 已提交
71
		s.Host,
A
astaxie 已提交
72
		auth,
1
1fei 已提交
73 74
		s.Username,
		s.RecipientAddresses,
A
astaxie 已提交
75 76
		mailmsg,
	)
77

A
astaxie 已提交
78 79 80
	return err
}

F
FuXiaoHei 已提交
81
// implementing method. empty.
A
astaxie 已提交
82 83 84
func (s *SmtpWriter) Flush() {
	return
}
F
FuXiaoHei 已提交
85 86

// implementing method. empty.
A
astaxie 已提交
87 88 89 90 91 92 93
func (s *SmtpWriter) Destroy() {
	return
}

func init() {
	Register("smtp", NewSmtpWriter)
}