-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.go
126 lines (100 loc) · 2.47 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
package meilo
import (
"bytes"
"crypto/rand"
_ "embed"
"fmt"
"html"
"html/template"
"log"
"mime"
"os"
"path"
"strings"
"github.com/pkg/browser"
)
var genID = func() string {
id := make([]byte, 16)
_, err := rand.Read(id)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", id)
}
var (
//go:embed html-tmpl.html
htmlTemplate string
//dir is the directory where the email body will be saved before opening in the browser
dir string = os.TempDir()
)
type templConfig struct {
Bodies []body
Attachments []attachment
}
func send(e email) error {
if len(e.Bodies) == 0 {
return fmt.Errorf("meilo: no email bodies found")
}
content := fmt.Sprintf(
htmlTemplate,
html.EscapeString(e.Subject),
html.EscapeString(e.From),
strings.Join(e.To, ", "),
strings.Join(e.Cc, ", "),
strings.Join(e.Bcc, ", "),
html.EscapeString(e.Subject),
)
path, err := saveEmailBody(content, e)
if err != nil {
return fmt.Errorf("meilo: failed to save email body: %w", err)
}
if err := browser.OpenFile(path); err != nil {
return fmt.Errorf("meilo: failed to open email in browser: %w", err)
}
return nil
}
func saveEmailBody(content string, email email) (string, error) {
err := saveAttachmentFiles(email.Attachments)
if err != nil {
return "", fmt.Errorf("meilo: failed to save attachments: %w", err)
}
tmpl := template.Must(template.New("mail").Funcs(
template.FuncMap{
"contains": strings.Contains,
},
).Parse(content))
var tpl bytes.Buffer
err = tmpl.Execute(&tpl, templConfig{
Bodies: email.Bodies,
Attachments: email.Attachments,
})
if err != nil {
return "", fmt.Errorf("meilo: failed to execute template: %w", err)
}
filePath := fmt.Sprintf("%s.html", genID())
path := path.Join(dir, filePath)
err = os.WriteFile(path, tpl.Bytes(), 0644)
if err != nil {
return "", fmt.Errorf("meilo: failed to write email body: %w", err)
}
return path, nil
}
func saveAttachmentFiles(attachments []attachment) error {
for i, a := range attachments {
if len(a.Name) > 50 {
a.Name = a.Name[:50]
}
exts, err := mime.ExtensionsByType(a.ContentType)
if err != nil {
return fmt.Errorf("meilo: failed to get extension for attachment %s: %w", a.Name, err)
}
name := genID()
filePath := path.Join(dir, fmt.Sprintf("%s%s", name, exts[0]))
err = os.WriteFile(filePath, a.Data, 0644)
if err != nil {
return fmt.Errorf("meilo: failed to write attachment %s: %w", name, err)
}
attachments[i].Path = filePath
}
return nil
}