wulei 1 год назад
Родитель
Сommit
6db110a094
5 измененных файлов с 112 добавлено и 0 удалено
  1. 54 0
      mail/api.go
  2. 19 0
      mail/client.go
  3. 12 0
      mail/client_test.go
  4. 17 0
      mail/types.go
  5. 10 0
      mail/vars.go

+ 54 - 0
mail/api.go

@@ -0,0 +1,54 @@
+package mail
+
+import (
+	"fmt"
+	"log"
+	"net/smtp"
+	"strings"
+	"time"
+)
+
+func (mail *MailClient) SendPanicWarning(content string) (err error) {
+	e := Email{
+		From:     FROM_USERNAME,
+		PassWord: FROM_PASSWORD,
+		To:       TO_USERNAME,
+		Subject:  "panic",
+		Content:  content,
+	}
+	return mail.send(e)
+}
+
+func (mail *MailClient) SendCustomWarning(subject, content string) (err error) {
+	e := Email{
+		From:     FROM_USERNAME,
+		PassWord: FROM_PASSWORD,
+		To:       TO_USERNAME,
+		Subject:  subject,
+		Content:  content,
+	}
+	return mail.send(e)
+}
+
+func (mail *MailClient) send(e Email) (err error) {
+	now := time.Now().Format("2006-01-02 15:04:05")
+	e.Subject = fmt.Sprintf("AppName: %s Title: %s Time: %s", mail.AppName, e.Subject, now)
+	// 按需要的格式设置邮件内容
+	message := []byte("From: " + e.From + "\r\n" +
+		"To: " + e.To + "\r\n" +
+		"Subject: " + e.Subject + "\r\n" +
+		"\r\n" +
+		e.Content)
+
+	// 连接到 SMTP 服务器
+	auth := smtp.PlainAuth("", e.From, e.PassWord, mail.Server)
+
+	err = smtp.SendMail(fmt.Sprintf("%s:%s", mail.Server, mail.Port), auth, e.From, strings.Split(e.To, ","), []byte(message))
+	if err != nil {
+		log.Println("Email send is failed , Error:", err)
+		return
+	}
+
+	log.Println("Email send successfully!")
+	return
+}

+ 19 - 0
mail/client.go

@@ -0,0 +1,19 @@
+package mail
+
+type MailClient struct {
+	AppName string
+	Server  string
+	Port    string
+}
+
+func CreateDefaultMailApiClient(appName string) *MailClient {
+	return createMailApiClient(appName, SMTP_SERVER, SMTP_PORT)
+}
+
+func createMailApiClient(appName, server, port string) *MailClient {
+	return &MailClient{
+		AppName: appName,
+		Server:  server,
+		Port:    port,
+	}
+}

+ 12 - 0
mail/client_test.go

@@ -0,0 +1,12 @@
+package mail
+
+import (
+	"testing"
+)
+
+func TestCreateMailApiClient(t *testing.T) {
+	client := CreateDefaultMailApiClient()
+	err := client.SendSystemWarning("this is a test email!!!")
+
+	t.Log(err)
+}

+ 17 - 0
mail/types.go

@@ -0,0 +1,17 @@
+package mail
+
+// Email 邮箱
+type Email struct {
+	From     string // 发送方
+	PassWord string // 发送方-密码
+	To       string // 接收方,可逗号分割多个收件人
+	Subject  string // 主题
+	Content  string // 正文
+}
+
+type (
+	MailAPI interface {
+		SendPanicWarning(content string) (err error)
+		SendCustomWarning(subject, content string) (err error)
+	}
+)

+ 10 - 0
mail/vars.go

@@ -0,0 +1,10 @@
+package mail
+
+const (
+	SMTP_SERVER   = "smtp.qiye.aliyun.com"
+	SMTP_PORT     = "25"
+	FROM_USERNAME = "system_notify@greentech.com.cn"
+	FROM_PASSWORD = "GT123qweasd"
+
+	TO_USERNAME = "lei.wu@greentech.com.cn,qian.zhang@greentech.com.cn,yagang.gao@greentech.com.cn"
+)