This repository has been archived by the owner on Apr 28, 2023. It is now read-only.
generated from uberswe/golang-base-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (48 loc) · 1.71 KB
/
main.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
// Package email handles the sending of emails
package email
import (
"bytes"
"fmt"
"github.com/tournify/web/config"
"github.com/tournify/web/util"
"log"
"mime/multipart"
"net/smtp"
"strings"
)
type Service struct {
Config config.Config
}
func New(c config.Config) Service {
return Service{
Config: c,
}
}
func (s Service) Send(to string, subject string, message string) {
// Authentication.
auth := smtp.PlainAuth("", s.Config.SMTPUsername, s.Config.SMTPPassword, s.Config.SMTPHost)
// RFC #822 Standard
writer := multipart.NewWriter(bytes.NewBufferString(""))
var b bytes.Buffer
_, _ = fmt.Fprintf(&b, "From: %s\r\nTo: %s\r\nSubject: %s\r\n", s.Config.SMTPSender, to, subject)
_, _ = fmt.Fprintf(&b, "MIME-Version: 1.0\r\n")
_, _ = fmt.Fprintf(&b, "Content-Type: multipart/alternative; charset=\"UTF-8\"; boundary=\"%s\"\r\n", writer.Boundary())
_, _ = fmt.Fprintf(&b, "\r\n\r\n--%s\r\nContent-Type: %s; charset=UTF-8;\nContent-Transfer-Encoding: 8bit\r\n\r\n", writer.Boundary(), "text/plain")
b.Write([]byte(message))
htmlMessage := util.StringLinkToHTMLLink(message)
htmlMessage = util.NL2BR(htmlMessage)
_, _ = fmt.Fprintf(&b, "\r\n\r\n--%s\r\nContent-Type: %s; charset=UTF-8;\nContent-Transfer-Encoding: 8bit\r\n\r\n", writer.Boundary(), "text/html")
b.Write([]byte(htmlMessage))
_, _ = fmt.Fprintf(&b, "\r\n\r\n--%s--\r\n", writer.Boundary())
sender := s.Config.SMTPSender
if strings.Contains(sender, "<") {
sender = util.GetStringBetweenStrings(sender, "<", ">")
}
// Sending email.
err := smtp.SendMail(fmt.Sprintf("%s:%s", s.Config.SMTPHost, s.Config.SMTPPort), auth, sender, []string{to}, b.Bytes())
if err != nil {
log.Println(err)
return
}
log.Println(fmt.Sprintf("Email sent to %s", to))
}