all repos — navani @ ea8ad151310499d429bb7aa02cdb4acdac813db0

forlater's primary mail processing service

mail/utils.go (view raw)

 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
package mail

import (
	"fmt"

	"github.com/microcosm-cc/bluemonday"
	"mvdan.cc/xurls/v2"
)

type Mail struct {
	From    string
	Date    string
	ReplyTo string
	Body    string
	Parts   map[string]string
}

// TODO
// // Strips the signature from an email.
// func stripSignature(text string) string {
// 	lines := strings.Split(text, "\n")
// 	stripped := []string{}
// 	for i := len(lines) - 1; i >= 0; i-- {
// 		if lines[i] == "--" || lines[i] == "-- " {
// 			break
// 		}
// 		stripped = append(stripped, lines[i])
// 	}
// 	return strings.Join(stripped, "\n")
// }

// Extracts URLs from given text.
func ExtractURLs(text string) []string {
	x := xurls.Strict()
	return x.FindAllString(text, -1)
}

// Returns the main body of the email; hopefully containing URLs.
func MailBody(parts map[string]string) (string, error) {
	if plain, ok := parts["text/plain"]; ok {
		return plain, nil
	} else if html, ok := parts["text/html"]; ok {
		p := bluemonday.NewPolicy()
		p.AllowStandardURLs()
		p.AddSpaceWhenStrippingTag(true)
		clean := p.Sanitize(html)
		return clean, nil
	} else {
		return "", fmt.Errorf("no good MIME type found")
	}
}