all repos — navani @ f2a4424f62c16474a01d8313cff63d0aa9e9e8fc

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

import (
	"fmt"

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

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

// 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")
	}
}