Documentation
¶
Overview ¶
Package mail parses MIME messages and sanitizes HTML bodies. It is pure: no storage, network or UI dependencies.
Index ¶
- Constants
- func ASCIIHost(host string) string
- func ActionLink(subject, text, htmlBody string) (link, kind string)
- func AddrKey(s string) string
- func BIMICertPool() *x509.CertPool
- func Blank(src string) bool
- func Build(o Outgoing, now time.Time) (raw []byte, messageID string, err error)
- func CIDs(src string) []string
- func CutUTF8(s string, n int) (string, bool)
- func DecodePart(data []byte, encoding, cs string) ([]byte, error)
- func EmphasizedCode(subject, text, htmlBody string) string
- func FormatAddress(name, addr string) string
- func ForwardSubject(s string) string
- func FromSelf(from, replyTo, self string) bool
- func GroupCode(code string) string
- func HTMLToText(src string) string
- func HasDisplayDomainMismatch(displayName, domain string) bool
- func HasSuspiciousDomainPattern(domain string) bool
- func HasZeroWidthEvasion(s string) bool
- func IsForwardSubject(s string) bool
- func IsFreemail(domain string) bool
- func IsKnownBrandSpoof(displayName, domain string) (bool, string)
- func IsManualSecurity(reason string) bool
- func JoinDraft(editable, quote, signature string) string
- func LinkHost(link string) string
- func LookupBIMI(ctx context.Context, domain string, dmarcPass bool) bool
- func ManualSecurityStatus(reason string) (status string, ok bool)
- func MapHTMLText(src string, replace func(string) string) string
- func NeedsDKIMVerification(from, authResults string, signed bool) bool
- func NormalizeConfusables(s string) string
- func ParseStructure(bs imap.BodyStructure) (textParts []Attachment, atts []Attachment)
- func PrimaryButton(subject, text, htmlBody string) (link, kind string)
- func QuoteHTML(orig *Parsed) string
- func QuoteHTMLIn(orig *Parsed, lang string) string
- func ReceiverAuthenticationResults(trace []AuthenticationHeader, _ ...string) string
- func RemoteImages(safe string) []string
- func ReplaceImages(src string, f func(s string) string) string
- func ReplyRecipients(orig *Parsed, self string, all bool) (to, cc []string)
- func ReplySubject(s string) string
- func Sanitize(src string, inline map[string]Attachment, loadRemote bool) (safe string, blockedRemote, trackers int)
- func SanitizeCompose(src string) string
- func SanitizeDraft(src string, cids map[string]bool) string
- func SanitizeLazy(src string, known map[string]Attachment, loadRemote bool) (safe string, blockedRemote, trackers int)
- func SecurityRank(s SecurityStatus) int
- func SecurityReportToDB(rep SecurityReport) (status string, reason string)
- func SignInCode(subject, text, htmlBody string) string
- func Snippet(text string) string
- func SplitDraft(src string) (editable, quote, signature string)
- func StripInvisible(text string) string
- func StripMarkers(src string) string
- func ThreadKeys(p *Parsed) (ids []string, subjectKey string)
- func ValidText(b []byte, cs string, isHTML bool) []byte
- func VisibleText(src string) string
- type Attachment
- type AuthenticationHeader
- type Mailto
- type Outgoing
- type Parsed
- type SecurityReport
- type SecurityStatus
- type WarningKind
Constants ¶
const ( MaxBodyBytes = 2 << 20 MaxMIMEDepth = 20 )
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.
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.
const MaxListHeaderBytes = 2 << 10
MaxListHeaderBytes is the longest List-* header kept; a longer one counts as absent.
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.
const SecurityVerified = SecurityVerifiedDomain
SecurityVerified is kept as an alias for SecurityVerifiedDomain.
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
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 ¶ added in v1.5.0
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 BIMICertPool ¶ added in v1.21.0
BIMICertPool returns a certificate pool containing the trusted BIMI root authorities.
func Blank ¶
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 ¶
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 CutUTF8 ¶ added in v1.20.1
CutUTF8 keeps at most n bytes of s, at a rune boundary, and reports whether it cut.
func DecodePart ¶
DecodePart decodes a separately fetched MIME part body using its recorded transfer encoding and (for text) charset.
func EmphasizedCode ¶ added in v1.9.0
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 ¶
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 FromSelf ¶ added in v1.27.0
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
GroupCode splits a six-digit code in two, as people read it ("482 913").
func HTMLToText ¶
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
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
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
HasZeroWidthEvasion checks if a string contains invisible zero-width or directional control characters commonly used by attackers to evade spam filters and tokenizers.
func IsForwardSubject ¶ added in v1.29.0
IsForwardSubject reports whether s starts with a forward prefix, as every subject from ForwardSubject does.
func IsFreemail ¶ added in v1.21.0
IsFreemail returns true if the domain is a known public webmail provider.
func IsKnownBrandSpoof ¶ added in v1.21.0
IsKnownBrandSpoof checks if a display name imitates a known brand on an unauthorized domain.
func IsManualSecurity ¶ added in v1.26.0
IsManualSecurity reports whether reason is a user's classification.
func LookupBIMI ¶ added in v1.21.0
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
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
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
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
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
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 ¶
QuoteHTML returns the "on {date}, {from} wrote:" line plus the original in a blockquote.
func QuoteHTMLIn ¶ added in v1.7.0
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
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 ¶
ReplaceImages returns src with every <img> source s replaced by f(s); an empty result drops the source. It does not sanitize.
func ReplyRecipients ¶
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 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 ¶
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 ¶
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 SanitizeLazy ¶ added in v1.29.0
func SanitizeLazy(src string, known map[string]Attachment, loadRemote bool) (safe string, blockedRemote, trackers int)
SanitizeLazy is Sanitize for a reader that loads the inline images itself: an image of a Content-ID in known keeps its src as cid:<id>, the data unread.
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
SignInCode recognizes an explicit code in the subject or unquoted text. Conflicting candidates are left to the reader rather than guessed.
func Snippet ¶
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 ¶
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
StripInvisible drops the characters of text that show nothing (invisible), so the joiners stay: inside a word they shape it.
func StripMarkers ¶
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 ¶
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
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
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
Mailto is a mailto: URI's draft (RFC 6068).
func ParseMailto ¶ added in v1.14.0
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
}
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 )