-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail_sender.go
80 lines (58 loc) · 1.55 KB
/
mail_sender.go
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
73
74
75
76
77
78
79
80
package main
import (
"bytes"
"crypto/tls"
"fmt"
"time"
"github.com/russross/blackfriday"
"github.com/satori/go.uuid"
"github.com/go-mail/mail"
)
//MailMessageSender sends emails
type MailMessageSender struct {
Config SMTPConfig
}
//Send sends a message
func (s MailMessageSender) Send(msg Message) (SendMessageResult, error) {
result := SendMessageResult{
MessageID: uuid.NewV4().String(),
Date: time.Now(),
}
//Validation
result.Errors = validateMailMessage(&msg)
if len(result.Errors) > 0 {
return result, nil
}
//Preparing content
m := mail.NewMessage()
if msg.Type == PlainMail {
m.SetBody("text/plain", msg.Content)
} else if msg.Type == RichFormatMail {
contentBuffer := bytes.NewBufferString(msg.Content)
output := blackfriday.Run(contentBuffer.Bytes())
m.SetBody("text/html", string(output))
}
m.SetHeader("Subject", msg.Subject)
if len(msg.CC) > 0 {
m.SetHeader("Cc", msg.CC...)
}
//m.Attach("/home/Alex/lolcat.jpg")
var (
sender mail.SendCloser
err error
)
d := mail.NewDialer(s.Config.Host, s.Config.Port, s.Config.Username, s.Config.Password)
d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
d.Timeout = time.Second * time.Duration(s.Config.Timeout)
//
if sender, err = d.Dial(); err != nil {
return result, fmt.Errorf("error dialing remote smtp server: %s", err)
}
defer sender.Close()
// Send the email
if err := sender.Send(msg.From, msg.To, m); err != nil {
return result, fmt.Errorf("error sending message: %s", err)
}
result.Success = len(result.Errors) == 0
return result, nil
}