-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_sender.go
More file actions
72 lines (59 loc) · 1.57 KB
/
email_sender.go
File metadata and controls
72 lines (59 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package email
import (
"crypto/tls"
"encoding/json"
"time"
dgctx "github.com/darwinOrg/go-common/context"
dglogger "github.com/darwinOrg/go-logger"
"github.com/darwinOrg/go-monitor"
"gopkg.in/gomail.v2"
)
type SendEmailClient struct {
dialer *gomail.Dialer
UseMonitor bool
}
type SendEmailRequest struct {
To []string
Subject string
Content string
Attachments []string
}
func NewSendEmailClient(host string, port int, username string, password string) *SendEmailClient {
dialer := &gomail.Dialer{
Host: host,
Port: port,
Username: username,
Password: password,
SSL: false,
TLSConfig: &tls.Config{InsecureSkipVerify: true},
}
return &SendEmailClient{dialer: dialer, UseMonitor: true}
}
func (s *SendEmailClient) SendEmail(ctx *dgctx.DgContext, request *SendEmailRequest) error {
if s.UseMonitor {
monitor.HttpClientCounter(s.dialer.Host)
}
start := time.Now().UnixMilli()
m := gomail.NewMessage()
m.SetHeader("From", s.dialer.Username)
m.SetHeader("To", request.To...)
m.SetHeader("Subject", request.Subject)
m.SetBody("text/html", request.Content)
if request.Attachments != nil && len(request.Attachments) > 0 {
for _, attachment := range request.Attachments {
m.Attach(attachment)
}
}
requestJson, _ := json.Marshal(request)
err := s.dialer.DialAndSend(m)
cost := time.Now().UnixMilli() - start
if s.UseMonitor {
e := "false"
if err != nil {
e = "true"
}
monitor.HttpClientDuration(s.dialer.Host, e, cost)
}
dglogger.Infof(ctx, "send email: %s, cost: %d ms", requestJson, cost)
return err
}