aboutsummaryrefslogtreecommitdiff
path: root/lib/address.go
blob: b557195b46fe861013b401565ecfcf0e4ac48e76 (plain)
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
package lib

import (
	"bytes"
	"fmt"
	"regexp"
	"strings"

	"github.com/emersion/go-imap"
)

var (
	atom *regexp.Regexp = regexp.MustCompile("^[a-z0-9!#$%7'*+-/=?^_`{}|~ ]+$")
)

func FormatAddresses(addrs []*imap.Address) string {
	val := bytes.Buffer{}
	for i, addr := range addrs {
		val.WriteString(FormatAddress(addr))
		if i != len(addrs)-1 {
			val.WriteString(", ")
		}
	}
	return val.String()
}

func FormatAddress(addr *imap.Address) string {
	if addr.PersonalName != "" {
		if atom.MatchString(addr.PersonalName) {
			return fmt.Sprintf("%s <%s@%s>",
				addr.PersonalName, addr.MailboxName, addr.HostName)
		} else {
			return fmt.Sprintf("\"%s\" <%s@%s>",
				strings.ReplaceAll(addr.PersonalName, "\"", "'"),
				addr.MailboxName, addr.HostName)
		}
	} else {
		return fmt.Sprintf("<%s@%s>", addr.MailboxName, addr.HostName)
	}
}