all repos — navani @ 2928def670071abf79a9dd21ecbaa532149405f4

forlater's primary mail processing service

mail/utils.go (view raw)

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