Parse Addresses With net mail
Parse raw To and From headers with net/mail ParseAddress and ParseAddressList, keeping the display name separate from the routed address.
Code
package main
import (
"fmt"
"net/mail"
)
func main() {
// 单个地址:显示名与实际路由地址分开解析
from, err := mail.ParseAddress("Ada Lovelace <[email protected]>")
if err != nil {
fmt.Println("reject:", err)
return
}
fmt.Println("name:", from.Name, "addr:", from.Address)
// 收件人列表:一次解析整串 To 头
toList, err := mail.ParseAddressList("Ops <[email protected]>, [email protected]")
if err != nil {
fmt.Println("reject list:", err)
return
}
for _, a := range toList {
fmt.Printf("to: %s <%s>\n", a.Name, a.Address)
}
// 缺失或畸形地址被拒绝,而不是静默放行
if _, err := mail.ParseAddress("not-an-address"); err != nil {
fmt.Println("bad input rejected:", err)
}
}What the code does
Parse Addresses With net mail reduces to the function main.
Repetition is confined to for _, a := range toList — the rest of the file is straight-line. Error handling is inline: 3 places test err != nil and branch immediately.
Applying it
The demo output is labeled (reject:, name:, reject list:), so the printed lines read as a trace of the operations that ran.
Statements that decide the outcome
for _, a := range toList {
fmt.Printf("to: %s <%s>\n", a.Name, a.Address)
}
if err != nil {
fmt.Println("reject:", err)
return
}
if err != nil {
fmt.Println("reject list:", err)
return
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.Quoted-Printable CodecEncode and decode quoted-printable (RFC 2045) used by email, escaping non-ASCII bytes and wrapping long lines.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Parse Addresses With net mail print when run?
- Execute the whole file; each printed line is prefixed with a label like `reject:`, `name:`, `reject list:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.