forked from yukifujiismtp/go-email
/
sender.go
55 lines (44 loc) · 1.22 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package email
import (
"errors"
"net/mail"
"net/smtp"
)
// Send this email using the SMTP Address:Port, and optionally any SMTP Auth.
// Send will call Save() on the message before sending.
func (m *Message) Send(smtpAddressPort string, auth smtp.Auth) error {
to := m.Header.To()
cc := m.Header.Cc()
bcc := m.Header.Bcc()
all := make([]string, 0, len(to)+len(cc)+len(bcc))
all = append(append(append(all, to...), cc...), bcc...)
for i := 0; i < len(all); i++ {
address, err := mail.ParseAddress(all[i])
if err != nil {
return err
}
all[i] = address.Address
}
if len(all) == 0 {
return errors.New("May not send email without a recipient (To, CC, or Bcc)")
}
from, err := mail.ParseAddress(m.Header.From())
if err != nil {
return err
}
if len(from.Address) == 0 {
return errors.New("May not send email without a From address")
}
err = m.Save()
if err != nil {
return err
}
b, err := m.Bytes()
if err != nil {
return err
}
return smtp.SendMail(smtpAddressPort, auth, from.Address, all, b)
}