This repository has been archived by the owner on Jun 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
mail.go
88 lines (77 loc) · 2.17 KB
/
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
package main
import (
"bytes"
"fmt"
"github.com/jordan-wright/email"
"net/mail"
"net/smtp"
)
const (
commentsUrl = "https://news.ycombinator.com/item?id=%d"
)
// auth sets up SMTP account credentials.
func auth() smtp.Auth {
return smtp.PlainAuth("", config.SMTP.User, config.SMTP.Password, config.SMTP.Host)
}
// loadEmail applies the given data to a particular email template, returning the output bytes.
func loadEmail(templ string, data interface{}) ([]byte, error) {
var doc bytes.Buffer
err := useTemplate(templ, data, &doc)
return doc.Bytes(), err
}
// sendVerification delivers an email with the account verification link.
func sendVerification(to, link string) {
subject := "HN Notifications - Email verification needed"
message, err := loadEmail("activate_email", map[string]string{"link": link})
if err != nil {
Logger.Println("Error: sendVerification() - ", err)
return
}
e := email.NewEmail()
e.From = config.Email
e.To = []string{to}
e.Subject = subject
e.HTML = message
err = e.Send(config.SMTP.Addr, auth())
if err != nil {
Logger.Println("Error: sendVerification() - ", err)
}
}
// sendUnsubscription delivers an email with the unsubscription link.
func sendUnsubscription(to, link string) error {
subject := "HN Notifications - Unsubscribe"
message, err := loadEmail("unsubscribe_email", map[string]string{"link": link})
if err != nil {
return err
}
e := email.NewEmail()
e.From = config.Email
e.To = []string{to}
e.Subject = subject
e.HTML = message
return e.Send(config.SMTP.Addr, auth())
}
// sendItem delivers a notification email for the given item.
func sendItem(id int, title, url string, bcc []string) error {
data := map[string]string{
"title": title,
"link": url,
"discussion": fmt.Sprintf(commentsUrl, id),
"settings": config.Url + "/settings",
}
message, err := loadEmail("item_email", data)
if err != nil {
return err
}
e := email.NewEmail()
e.From = config.Email
e.Bcc = bcc
e.Subject = title
e.HTML = message
return e.Send(config.SMTP.Addr, auth())
}
// validateAddress is a simple email validation function.
func validateAddress(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}