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.

GoData Integrity

Code

gosnippet
31 lines
package main

import (
	"fmt"
	"net/mail"
)

func main() {
	// 单个地址:显示名与实际路由地址分开解析
	from, err := mail.ParseAddress("Ada Lovelace <ada@example.com>")
	if err != nil {
		fmt.Println("reject:", err)
		return
	}
	fmt.Println("name:", from.Name, "addr:", from.Address)

	// 收件人列表:一次解析整串 To 头
	toList, err := mail.ParseAddressList("Ops <ops@example.com>, bob@example.com")
	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

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:`.