mail/utils.go (view raw)
1package mail
2
3import (
4 "fmt"
5
6 "github.com/microcosm-cc/bluemonday"
7 "mvdan.cc/xurls/v2"
8)
9
10type Mail struct {
11 From string
12 Date string
13 ReplyTo string
14 Body string
15 Parts map[string]string
16}
17
18// TODO
19// // Strips the signature from an email.
20// func stripSignature(text string) string {
21// lines := strings.Split(text, "\n")
22// stripped := []string{}
23// for i := len(lines) - 1; i >= 0; i-- {
24// if lines[i] == "--" || lines[i] == "-- " {
25// break
26// }
27// stripped = append(stripped, lines[i])
28// }
29// return strings.Join(stripped, "\n")
30// }
31
32// Extracts URLs from given text.
33func ExtractURLs(text string) []string {
34 x := xurls.Strict()
35 return x.FindAllString(text, -1)
36}
37
38// Returns the main body of the email; hopefully containing URLs.
39func MailBody(parts map[string]string) (string, error) {
40 if plain, ok := parts["text/plain"]; ok {
41 return plain, nil
42 } else if html, ok := parts["text/html"]; ok {
43 p := bluemonday.NewPolicy()
44 p.AllowStandardURLs()
45 p.AddSpaceWhenStrippingTag(true)
46 clean := p.Sanitize(html)
47 return clean, nil
48 } else {
49 return "", fmt.Errorf("no good MIME type found")
50 }
51}