mail

package
v1.27.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 44 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mail parses MIME messages and sanitizes HTML bodies. It is pure: no storage, network or UI dependencies.

Index

Constants

View Source
const (
	MaxBodyBytes = 2 << 20
	MaxMIMEDepth = 20
)
View Source
const (
	LinkSignIn  = "signin"  // signs in: a magic link
	LinkConfirm = "confirm" // confirms the address a new account was made with
	LinkReset   = "reset"   // sets a new password
)

The kinds of action link ActionLink finds.

View Source
const ManualSecuritySQL = "('manual_safe', 'manual_suspicious', 'manual_warning')"

ManualSecuritySQL is the SQL list of the manual reasons, for the scans and syncs that must leave a user's classification alone.

View Source
const MaxListHeaderBytes = 2 << 10

MaxListHeaderBytes is the longest List-* header kept; a longer one counts as absent.

View Source
const RuleHeader = "X-Godwit-Rule"

RuleHeader marks mail a Godwit rule forwarded; mail carrying it is never forwarded by a rule again, so two rules can't forward in a loop.

View Source
const SecurityVerified = SecurityVerifiedDomain

SecurityVerified is kept as an alias for SecurityVerifiedDomain.

View Source
const SecurityWarning = SecurityFraud

SecurityWarning is kept as an alias for backwards compatibility.

Variables

This section is empty.

Functions

func ASCIIHost added in v1.20.1

func ASCIIHost(host string) string

ASCIIHost is host as shown before a link is followed: in punycode (xn--…) when it has a non-ASCII letter, so a look-alike such as Cyrillic "аpple.com" does not pass for apple.com.

func ActionLink(subject, text, htmlBody string) (link, kind string)

ActionLink recognizes the one link a mail asks the reader to open to sign in, to confirm a new account's address, or to set a new password, and which it is. Conflicting links are left to the reader rather than guessed.

func AddrKey

func AddrKey(s string) string

AddrKey is the lowercased bare address of an address string ("Bob <b@x>" → "b@x").

func BIMICertPool added in v1.21.0

func BIMICertPool() *x509.CertPool

BIMICertPool returns a certificate pool containing the trusted BIMI root authorities.

func Blank

func Blank(src string) bool

Blank reports whether HTML has no content at all: only whitespace and the editor's empty placeholders (p, div, br). An image, a rule or a table is content.

func Build

func Build(o Outgoing, now time.Time) (raw []byte, messageID string, err error)

Build renders o as RFC 5322 bytes. Bcc is never written to the headers (the sender uses it only as envelope recipients). messageID is returned without angle brackets, matching Parsed.MessageID.

func CIDs

func CIDs(src string) []string

CIDs are the Content-IDs src's images refer to as cid:, in order.

func CutUTF8 added in v1.20.1

func CutUTF8(s string, n int) (string, bool)

CutUTF8 keeps at most n bytes of s, at a rune boundary, and reports whether it cut.

func DecodePart

func DecodePart(data []byte, encoding, cs string) ([]byte, error)

DecodePart decodes a separately fetched MIME part body using its recorded transfer encoding and (for text) charset.

func EmphasizedCode added in v1.9.0

func EmphasizedCode(subject, text, htmlBody string) string

EmphasizedCode is the one code an HTML body sets apart: alone in its block, shown large, bold, letter-spaced or monospaced. "" for none or several.

func FormatAddress

func FormatAddress(name, addr string) string

FormatAddress renders a display name and address as one header address that net/mail parses back to the same parts. The name stays readable UTF-8 and is quoted (with \ and " escaped) unless it is a plain run of words; so is a local part that is not a dot-atom ("a b"@example.com).

func ForwardSubject

func ForwardSubject(s string) string

func FromSelf added in v1.27.0

func FromSelf(from, replyTo, self string) bool

FromSelf reports whether a mail from from (with Reply-To replyTo, "" for none) is the user's own at self: a reply to it goes to its recipients.

func GroupCode added in v1.5.0

func GroupCode(code string) string

GroupCode splits a six-digit code in two, as people read it ("482 913").

func HTMLToText

func HTMLToText(src string) string

HTMLToText converts HTML to plain text: block elements become line breaks, list items get a "- " prefix, links render as "text (url)".

func HasDisplayDomainMismatch added in v1.21.0

func HasDisplayDomainMismatch(displayName, domain string) bool

HasDisplayDomainMismatch checks if the display name represents an organization or brand that clearly contradicts the sender's actual domain.

func HasSuspiciousDomainPattern added in v1.21.0

func HasSuspiciousDomainPattern(domain string) bool

HasSuspiciousDomainPattern checks for machine-generated / disposable spam domain patterns, such as long digit sequences (>= 6 digits) often used in disposable campaign domains.

func HasZeroWidthEvasion added in v1.21.0

func HasZeroWidthEvasion(s string) bool

HasZeroWidthEvasion checks if a string contains invisible zero-width or directional control characters commonly used by attackers to evade spam filters and tokenizers.

func IsFreemail added in v1.21.0

func IsFreemail(domain string) bool

IsFreemail returns true if the domain is a known public webmail provider.

func IsKnownBrandSpoof added in v1.21.0

func IsKnownBrandSpoof(displayName, domain string) (bool, string)

IsKnownBrandSpoof checks if a display name imitates a known brand on an unauthorized domain.

func IsManualSecurity added in v1.26.0

func IsManualSecurity(reason string) bool

IsManualSecurity reports whether reason is a user's classification.

func JoinDraft

func JoinDraft(editable, quote, signature string) string

JoinDraft is the draft body of its parts, as SplitDraft returns them.

func LinkHost added in v1.5.0

func LinkHost(link string) string

LinkHost is where a link really goes, shown before it opens.

func LookupBIMI added in v1.21.0

func LookupBIMI(ctx context.Context, domain string, dmarcPass bool) bool

LookupBIMI checks whether the domain has a published BIMI record with a valid, verified mark certificate (VMC) signed by an approved authority (DigiCert or Entrust). According to the BIMI specification, BIMI can only be valid if DMARC passes.

func ManualSecurityStatus added in v1.26.0

func ManualSecurityStatus(reason string) (status string, ok bool)

ManualSecurityStatus is the security_status a user's classification (the reason manual_safe, manual_suspicious or manual_warning) is stored under, so every reader of the column ranks it like a scanned verdict. A safe mark is neutral: it never claims a verified domain the headers did not prove.

func MapHTMLText added in v1.2.0

func MapHTMLText(src string, replace func(string) string) string

MapHTMLText replaces prose text nodes, leaving code, markup and attributes intact. The callback's result is text: html.Render escapes it, including any model markup.

func NeedsDKIMVerification added in v1.21.0

func NeedsDKIMVerification(from, authResults string, signed bool) bool

NeedsDKIMVerification schedules an automatic local check only when there is a signature and no trusted positive/native warning or freemail exclusion.

func NormalizeConfusables added in v1.21.0

func NormalizeConfusables(s string) string

NormalizeConfusables normalizes display names by converting common homoglyphs / confusables (such as Cyrillic or Greek lookalikes and fullwidth characters) into ASCII Latin equivalents, and removes invisible zero-width and directional control characters.

func ParseStructure

func ParseStructure(bs imap.BodyStructure) (textParts []Attachment, atts []Attachment)

ParseStructure walks an IMAP BODYSTRUCTURE and reports the displayable body parts to fetch and the attachment metadata, with IMAP part paths. ponytail: message/rfc822 children are treated as one attachment, not descended into.

func PrimaryButton added in v1.9.0

func PrimaryButton(subject, text, htmlBody string) (link, kind string)

PrimaryButton is the one https link an HTML body draws as a button, and what it does: confirming an address or setting a password when the mail speaks of that, else signing in. "" for none, several, or a security alert, whose button reviews activity.

func QuoteHTML

func QuoteHTML(orig *Parsed) string

QuoteHTML returns the "on {date}, {from} wrote:" line plus the original in a blockquote.

func QuoteHTMLIn added in v1.7.0

func QuoteHTMLIn(orig *Parsed, lang string) string

QuoteHTMLIn formats QuoteHTML with the attribution line in lang ("" or zh-Hans defaults to Simplified Chinese).

func ReceiverAuthenticationResults added in v1.21.0

func ReceiverAuthenticationResults(trace []AuthenticationHeader, _ ...string) string

ReceiverAuthenticationResults returns the topmost Authentication-Results group. Receiving services prepend theirs above the trace, so it sits above anything the sender wrote; Gmail and iCloud put it below their own Received. shortcut: a receiver that adds no result of its own leaves the sender's on top; trust only configured authserv-ids if that shows up in practice.

func RemoteImages added in v0.1.0

func RemoteImages(safe string) []string

RemoteImages are the http(s) image sources of a sanitized body (kept by Sanitize with loadRemote): its <img> sources and CSS background images, in order, each once.

func ReplaceImages

func ReplaceImages(src string, f func(s string) string) string

ReplaceImages returns src with every <img> source s replaced by f(s); an empty result drops the source. It does not sanitize.

func ReplyRecipients

func ReplyRecipients(orig *Parsed, self string, all bool) (to, cc []string)

ReplyRecipients picks reply targets: Reply-To if set, else From. With all, the original To/Cc are added to cc. self and duplicates are dropped. A reply to the user's own mail (From is self, no other Reply-To) follows up with its recipients instead: the original To, plus Cc with all.

func ReplySubject

func ReplySubject(s string) string

func Sanitize

func Sanitize(src string, inline map[string]Attachment, loadRemote bool) (safe string, blockedRemote, trackers int)

Sanitize cleans received HTML. inline is keyed by Content-ID. Links become data-href (not navigable); remote images are dropped unless loadRemote. blockedRemote counts remote resources found in the original HTML; trackers counts the tracking pixels, dropped whatever loadRemote says.

func SanitizeCompose

func SanitizeCompose(src string) string

SanitizeCompose cleans pasted content in the composer: same whitelist, no remote resources. data-godwit survives only as a draft marker: "quote" or "signature".

func SanitizeDraft

func SanitizeDraft(src string, cids map[string]bool) string

SanitizeDraft is SanitizeCompose keeping the images whose src is cid: of a Content-ID in cids (the draft account's signature images); any other cid, data: or remote source is dropped.

func SecurityRank added in v1.21.0

func SecurityRank(s SecurityStatus) int

SecurityRank returns display priority: Rot (5) > Gelb (4) > Blau (3) > Grün (2) > Grau (1).

func SecurityReportToDB added in v1.21.0

func SecurityReportToDB(rep SecurityReport) (status string, reason string)

SecurityReportToDB converts a SecurityReport into (status, reason) strings for SQL persistence.

func SignInCode added in v1.5.0

func SignInCode(subject, text, htmlBody string) string

SignInCode recognizes an explicit code in the subject or unquoted text. Conflicting candidates are left to the reader rather than guessed.

func Snippet

func Snippet(text string) string

Snippet returns the first 200 characters with whitespace collapsed and the invisible characters gone: mail pads its preview text with zero-width and joiner characters between spaces (a preheader), which would fill the line with nothing to see. They are dropped, not made spaces, so none splits a word (a soft hyphen); the joiners only at a word's ends, as inside one they shape it (Persian's non-joiner, an emoji's joiner).

func SplitDraft

func SplitDraft(src string) (editable, quote, signature string)

SplitDraft splits a sanitized draft body into its editable part, its quote and its signature: the first top-level elements marked "quote" and "signature"; everything else is editable. JoinDraft puts them back together.

func StripInvisible added in v1.13.0

func StripInvisible(text string) string

StripInvisible drops the characters of text that show nothing (invisible), so the joiners stay: inside a word they shape it.

func StripMarkers

func StripMarkers(src string) string

StripMarkers removes every data-godwit attribute, in any letter case (the parser lowercases names), so marked HTML from a model or another mail becomes ordinary content.

func ThreadKeys

func ThreadKeys(p *Parsed) (ids []string, subjectKey string)

ThreadKeys returns the conversation keys of p: ids is its own Message-ID plus In-Reply-To and References (deduplicated), subjectKey the lowercased subject without Re/Fwd/回复/转发 prefixes and with whitespace collapsed.

func ValidText added in v1.11.0

func ValidText(b []byte, cs string, isHTML bool) []byte

ValidText makes a decoded text part valid UTF-8 when its declared charset cs did not: an HTML part's <meta charset> when MIME names none, else U+FFFD for the bad bytes. No guessing beyond that: byte ranges cannot tell GBK from EUC-KR or Shift_JIS, and mojibake stored as text is worse than U+FFFD.

func VisibleText added in v1.13.0

func VisibleText(src string) string

VisibleText is HTMLToText of what the reader shows of src, a body as Sanitize leaves it: without what styles hide from it and the characters that show nothing (StripInvisible). An element is gone when nothing inside it can show (concealed); text in a zero font size is gone, but not a descendant's that sets its own size. shortcut: only an element's own style counts, not a <style> rule hiding its class nor the font shorthand; read those too if hidden text turns up that way.

Types

type Attachment

type Attachment struct {
	Part, Encoding, Charset, Filename, ContentType, ContentID string
	Inline                                                    bool
	Size                                                      int
	Data                                                      []byte
}

Attachment Part is the IMAP-style 1-based dot path ("1", "2.1"). Data is empty when produced by ParseStructure.

type AuthenticationHeader added in v1.21.0

type AuthenticationHeader struct{ Key, Value string }

AuthenticationHeader preserves reception headers in their original wire order.

type Mailto added in v1.14.0

type Mailto struct {
	To, Cc, Bcc   []string
	Subject, Body string
}

Mailto is a mailto: URI's draft (RFC 6068).

func ParseMailto added in v1.14.0

func ParseMailto(link string) (Mailto, error)

ParseMailto reads a mailto: URI: the addresses of its path and its to field are To; cc, bcc, subject and body are kept, other fields ignored. Values are percent-decoded and + stays + (it is not form encoding); one with a bad escape ("50% off") is kept as written. The body's line breaks become \n, the subject's spaces.

type Outgoing

type Outgoing struct {
	From, ReplyTo string
	To, Cc, Bcc   []string
	Subject, HTML string
	InReplyTo     string
	References    []string
	Attachments   []Attachment // Data must be filled
	// Related are images the HTML may show as cid:<ContentID> (the account's
	// signature images): sent inline, in multipart/related, when it does.
	Related []Attachment
	Header  map[string]string // more header fields, such as RuleHeader
}

Outgoing is a message to be built. Addresses are "Name <addr>" or bare addresses.

type Parsed

type Parsed struct {
	MessageID, Subject, From, ReplyTo, InReplyTo string
	To, Cc, References                           []string
	Date                                         time.Time
	Text, HTML                                   string
	Truncated                                    bool
	Damaged                                      bool     // best-effort result: some part failed to read or decode
	Warnings                                     []string // what went wrong, for logs
	Attachments                                  []Attachment
	// The List-Unsubscribe, List-Unsubscribe-Post and List-Id headers as
	// sent, unfolded and trimmed; "" when absent or over MaxListHeaderBytes.
	ListUnsubscribe, ListUnsubscribePost, ListID string
	// AuthenticationResults contains only the selected receiving service's results.
	AuthenticationResults string
	AuthenticationTrace   []AuthenticationHeader
	DKIMSigned            bool
	RuleSent              bool // it has RuleHeader: a Godwit rule forwarded it
}

func Parse

func Parse(raw []byte) (*Parsed, error)

Parse parses a full RFC 5322 message.

type SecurityReport added in v1.21.0

type SecurityReport struct {
	Status             SecurityStatus
	WarningKind        WarningKind
	Reason             string
	BrandName          string
	ActualDomain       string
	DKIMPass           bool
	SPFPass            bool
	DMARCPass          bool
	BIMIPass           bool
	SuspiciousMismatch bool
}

SecurityReport holds the evaluation results for an email sender.

func DBToSecurityReport added in v1.21.0

func DBToSecurityReport(from, authResults, status, reason string) SecurityReport

DBToSecurityReport restores a SecurityReport from stored DB values and raw header info.

func EvaluateSecurity added in v1.21.0

func EvaluateSecurity(from string, authResults string) SecurityReport

EvaluateSecurity assesses whether the sender shows signs of spoofing or has verified authentication. authResults must be the receiving service's result selected by ReceiverAuthenticationResults, rather than an arbitrary Authentication-Results field from the message.

func VerifyMessageDKIM added in v1.21.0

func VerifyMessageDKIM(ctx context.Context, from string, raw []byte, lookup func(context.Context, string) ([]string, error)) (SecurityReport, error)

VerifyMessageDKIM verifies complete original message bytes, never the cached snippet/sanitized HTML. Only public DKIM/DMARC DNS records leave the device. A failed or unrelated signature grants no badge; temporary DNS errors retry.

type SecurityStatus added in v1.21.0

type SecurityStatus int

SecurityStatus indicates the authentication and spoofing assessment of a sender.

const (
	SecurityNeutral        SecurityStatus = iota // ⚪ Grau: Nicht bestätigt
	SecurityVerifiedDomain                       // 🟢 Grün: Domain bestätigt
	SecurityCertifiedBrand                       // 🔵 Blau: Zertifizierte Marke
	SecurityNeedsReview                          // 🟡 Gelb: Prüfung empfohlen
	SecurityFraud                                // 🔴 Rot: Starker Betrugsverdacht
)

type WarningKind added in v1.21.0

type WarningKind int

WarningKind specifies why a warning was triggered.

const (
	WarnNone WarningKind = iota
	WarnDisplaySpoof
	WarnEmailInName
	WarnAuthFailed
	WarnAIFraud
	WarnSuspicious
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL