Skip to content

Instantly share code, notes, and snippets.

@nl5887
Last active March 9, 2026 01:21
Show Gist options
  • Select an option

  • Save nl5887/8773c4fa20695a71c30c to your computer and use it in GitHub Desktop.

Select an option

Save nl5887/8773c4fa20695a71c30c to your computer and use it in GitHub Desktop.
Golang implementation for RFC 1342: Non-ASCII Mail Headers
package main
import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"mime/quotedprintable"
"regexp"
"strings"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/encoding/unicode"
)
func decoder(encoding string) (*encoding.Decoder, error) {
if strings.ToUpper(encoding) == "UTF-8" {
return unicode.UTF8.NewDecoder(), nil
} else if strings.ToUpper(encoding) == "ISO-8859-1" {
return charmap.ISO8859_1.NewDecoder(), nil
} else {
return nil, fmt.Errorf("Unknown encoding")
}
}
func decodeHeader(str string) (string, error) {
re := regexp.MustCompile(`\=\?(?P<charset>.*?)\?(?P<encoding>.*)\?(?P<body>.*?)\?(.*?)\=`)
matches := re.FindAllStringSubmatch(str, -1)
if len(matches) == 0 {
return str, nil
}
for _, match := range matches {
var r io.Reader = strings.NewReader(match[3])
if match[2] == "Q" {
r = quotedprintable.NewReader(r)
} else if match[2] == "B" {
r = base64.NewDecoder(base64.StdEncoding, r)
}
if d, err := decoder(match[1]); err == nil {
r = d.Reader(r)
}
if val, err := ioutil.ReadAll(r); err == nil {
str = strings.Replace(str, match[0], string(val), -1)
} else if err != nil {
fmt.Println(err.Error())
continue
}
}
return str, nil
}
func main() {
fmt.Println(decodeHeader("=?UTF-8?Q?=F3=BE=AC=8D_?= ... Laten we ontmoeten! Ik woon in de buurt .."))
fmt.Println(decodeHeader("=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment