-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsender.go
executable file
·239 lines (201 loc) · 5.21 KB
/
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package go_easy_mail
import (
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net/mail"
"net/smtp"
"os"
"path/filepath"
"strings"
)
type Mail struct {
Sender string
SenderName string
To []string
Cc []string
Bcc []string
Subject string
Body string
Attachments map[string][]byte
IsHTML bool
}
type GoEasyEmail struct {
host string
port string
userName string
password string
encryption bool
}
func NewGoEasyEmail(host, port, user, password string, encryption bool) *GoEasyEmail {
return &GoEasyEmail{
host: host,
port: port,
userName: user,
password: password,
encryption: encryption,
}
}
func (in *GoEasyEmail) Send(mail *Mail) (*Mail, error) {
var client *smtp.Client
var err error
var w io.WriteCloser
var receivers []string
var messageBody string = ""
if _, err = in.validateMail(mail); err != nil {
return mail, err
}
messageBody = in.buildMessage(mail)
app := newSMTPClient(in.host, in.port)
app.tlsConfig = &tls.Config{
InsecureSkipVerify: in.encryption,
ServerName: in.host,
}
if client, err = app.getClient(); err != nil {
return mail, err
}
// use auth
auth := smtp.PlainAuth("", in.userName, in.password, in.host)
if err = client.Auth(auth); err != nil {
return mail, err
}
// add all from and to
if err = client.Mail(mail.Sender); err != nil {
return mail, err
}
receivers = append(mail.To, mail.Cc...)
receivers = append(receivers, mail.Bcc...)
for _, k := range receivers {
if err = client.Rcpt(k); err != nil {
log.Println(err.Error())
}
}
// Data
if w, err = client.Data(); err != nil {
return mail, err
}
if _, err = w.Write([]byte(messageBody)); err != nil {
return mail, err
}
err = w.Close()
if err != nil {
log.Println(err.Error())
}
client.Quit()
// Mail sent successfully
return mail, nil
}
func (in *GoEasyEmail) buildMessage(mailDto *Mail) string {
var message strings.Builder
// MIME Header
message.WriteString("MIME-Version: 1.0\r\n")
message.WriteString("Content-Type: multipart/mixed; boundary=\"myboundary\"\r\n")
if mailDto.SenderName != "" {
from := &mail.Address{
Name: mailDto.SenderName,
Address: mailDto.Sender,
}
message.WriteString(fmt.Sprintf("From: %s\r\n", from.String()))
} else {
message.WriteString(fmt.Sprintf("From: %s\r\n", mailDto.Sender))
}
if len(mailDto.To) > 0 {
message.WriteString(fmt.Sprintf("To: %s\r\n", strings.Join(mailDto.To, ";")))
}
if len(mailDto.Cc) > 0 {
message.WriteString(fmt.Sprintf("Cc: %s\r\n", strings.Join(mailDto.Cc, ";")))
}
subject := base64.StdEncoding.EncodeToString([]byte(mailDto.Subject))
message.WriteString(fmt.Sprintf("Subject: =?utf-8?B?%s?=\r\n", subject))
message.WriteString("\r\n")
// Message body
message.WriteString("--myboundary\r\n")
if mailDto.IsHTML {
message.WriteString("Content-Type: text/html; charset=\"utf-8\"\r\n")
} else {
message.WriteString("Content-Type: text/plain; charset=\"utf-8\"\r\n")
}
message.WriteString("Content-Transfer-Encoding: 7bit\r\n")
message.WriteString("\r\n")
message.WriteString(mailDto.Body)
message.WriteString("\r\n")
// Attachments
for filename, data := range mailDto.Attachments {
message.WriteString("--myboundary\r\n")
contentType := in.getContentType(filename)
message.WriteString(fmt.Sprintf("Content-Type: %s; name=\"%s\"\r\n", contentType, filename))
message.WriteString("Content-Transfer-Encoding: base64\r\n")
message.WriteString(fmt.Sprintf("Content-Disposition: attachment; filename=\"%s\"\r\n", filename))
message.WriteString("\r\n")
message.WriteString(base64.StdEncoding.EncodeToString(data))
message.WriteString("\r\n")
}
message.WriteString("--myboundary--")
return message.String()
}
func (in *GoEasyEmail) getContentType(filename string) string {
ext := strings.ToLower(filepath.Ext(filename))
switch ext {
case ".txt":
return "text/plain"
case ".html":
return "text/html"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".png":
return "image/png"
case ".gif":
return "image/gif"
case ".pdf":
return "application/pdf"
case ".zip":
return "application/zip"
default:
return "application/octet-stream"
}
}
func (in *GoEasyEmail) validateMail(mail *Mail) (bool, error) {
errorEmailAddres := "email address is inavlid"
if mail.Body == "" {
return false, errors.New("must indicate a body")
}
if mail.Subject == "" {
return false, errors.New("must indicate a subject")
}
if !in.IsEmail(mail.Sender) {
return false, errors.New(errorEmailAddres)
}
if len(mail.To) <= 0 {
return false, errors.New("you must indicate at least one mail recipient")
}
for _, e := range mail.To {
if !in.IsEmail(e) {
return false, errors.New(errorEmailAddres)
}
}
for _, e := range mail.Cc {
if !in.IsEmail(e) {
return false, errors.New(errorEmailAddres)
}
}
for _, e := range mail.Bcc {
if !in.IsEmail(e) {
return false, errors.New(errorEmailAddres)
}
}
return true, nil
}
func (in *GoEasyEmail) IsEmail(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
func (in *GoEasyEmail) ReadFile(path string) []byte {
data, err := os.ReadFile(path)
if err != nil {
log.Fatalf("Failed to read file: %s", err)
}
return data
}