-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsend_mail.go
95 lines (68 loc) · 1.98 KB
/
send_mail.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bytes"
"fmt"
"mime/quotedprintable"
"net/smtp"
"strings"
)
/**
Modified from https://gist.github.com/jpillora/cb46d183eca0710d909a
Thank you very much.
**/
const (
/**
Gmail SMTP Server
**/
SMTPServer = "smtp.gmail.com"
)
type Sender struct {
User string
Password string
}
func NewSender(Username, Password string) Sender {
return Sender{Username, Password}
}
func (sender Sender) SendMail(Dest []string, Subject, bodyMessage string) {
msg := "From: " + sender.User + "\n" +
"To: " + strings.Join(Dest, ",") + "\n" +
"Subject: " + Subject + "\n" + bodyMessage
err := smtp.SendMail(SMTPServer+":587",
smtp.PlainAuth("", sender.User, sender.Password, SMTPServer),
sender.User, Dest, []byte(msg))
if err != nil {
fmt.Printf("smtp error: %s", err)
return
}
fmt.Println("Mail sent successfully!")
}
func (sender Sender) WriteEmail(dest []string, contentType, subject, bodyMessage string) string {
header := make(map[string]string)
header["From"] = sender.User
receipient := ""
for _, user := range dest {
receipient = receipient + user
}
header["To"] = receipient
header["Subject"] = subject
header["MIME-Version"] = "1.0"
header["Content-Type"] = fmt.Sprintf("%s; charset=\"utf-8\"", contentType)
header["Content-Transfer-Encoding"] = "quoted-printable"
header["Content-Disposition"] = "inline"
message := ""
for key, value := range header {
message += fmt.Sprintf("%s: %s\r\n", key, value)
}
var encodedMessage bytes.Buffer
finalMessage := quotedprintable.NewWriter(&encodedMessage)
finalMessage.Write([]byte(bodyMessage))
finalMessage.Close()
message += "\r\n" + encodedMessage.String()
return message
}
func (sender *Sender) WriteHTMLEmail(dest []string, subject, bodyMessage string) string {
return sender.WriteEmail(dest, "text/html", subject, bodyMessage)
}
func (sender *Sender) WritePlainEmail(dest []string, subject, bodyMessage string) string {
return sender.WriteEmail(dest, "text/plain", subject, bodyMessage)
}