Quoted-Printable Mail Body Encoding

Encode non-ASCII mail bodies with mime/quotedprintable so bytes become =XX escapes and soft line breaks keep lines under the 76-character limit.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"bytes"
	"fmt"
	"mime/quotedprintable"
	"strings"
)

func main() {
	body := "Übersicht: 完成, 100% ✓"

	// 编码:非 ASCII 字节变成 =XX 转义,等号本身转义为 =3D
	var encoded bytes.Buffer
	writer := quotedprintable.NewWriter(&encoded)
	if _, err := writer.Write([]byte(body)); err != nil {
		fmt.Println("encode:", err)
		return
	}
	if err := writer.Close(); err != nil {
		fmt.Println("flush:", err)
		return
	}
	fmt.Println("original:", body)
	fmt.Println("encoded :", encoded.String())

	// 解码:=XX 还原为原始字节,软换行(行尾 =)被剥掉
	decoded, err := quotedprintable.NewReader(strings.NewReader(encoded.String())).ReadAll()
	if err != nil {
		fmt.Println("decode:", err)
		return
	}
	fmt.Println("roundtrip equal:", string(decoded) == body)
}

How the snippet works

The snippet is organized around the function main.

Error handling is inline: 3 places test err != nil and branch immediately.

Watch out for

  • No third-party packages are used — the runtime ships every API called here.

Putting it to use

Entry signature: func main()

The file’s output announces each step as it happens: encode:, flush:, original:.

The core lines of the flow

if err != nil {
	fmt.Println("decode:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Quoted-Printable Mail Body Encoding print when run?
Running the file directly is enough — expect labeled output lines such as `encode:`, `flush:`, `original:`.