Golang : How to parse plain email text and process email header?
Problem :
Your program receive email in plain text and you need to parse email header information. How to that in Golang?
Solution :
First, convert the plain text into proper mail message type( see http://golang.org/pkg/net/mail/#Message ) with mail.ReadMessage()
function and then process the email header with the associated methods. See example code below.
package main
import (
"bytes"
"fmt"
"net/mail"
)
var emailData = `From: Adam <adam@earth.com>
To: Eve <eve@earth.com>
Subject: Do not eat the apple from that tree!
Date: Fri, 21 Nov 0000 09:55:06 -0600
Message-ID: <1234@garden.earth>
Don't listen to that snake. Don't eat the apple!
`
func main() {
msg, err := mail.ReadMessage(bytes.NewBuffer([]byte(emailData)))
if err != nil {
panic(err)
}
fmt.Println(msg.Header)
// --------------
header := msg.Header
key := "From"
address, err := header.AddressList(key)
if err != nil {
panic(err)
}
fmt.Println(address[0].String())
// --------------
key = "To"
addresses, err := header.AddressList(key)
if err != nil {
panic(err)
}
fmt.Println(addresses[0].String())
// --------------
dateTime, err := header.Date()
if err != nil {
panic(err)
}
fmt.Println(dateTime.String())
// --------------
getSubject := header.Get("Subject")
fmt.Println(getSubject)
}
Output :
map[Message-Id:[1234@garden.earth] From:[Adam adam@earth.com] To:[Eve eve@earth.com] Subject:[Do not eat the apple from that tree!] Date:[Fri,
21 Nov 0000 09:55:06 -0600]]
"Adam" adam@earth.com
"Eve" eve@earth.com
0000-11-21 09:55:06 -0600 -0600
Do not eat the apple from that tree!
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.8k Golang : Dealing with backquote
+6.9k Golang : How to fix html/template : "somefile" is undefined error?
+10.7k Golang : Replace a parameter's value inside a configuration file example
+24.9k Golang : Storing cookies in http.CookieJar example
+10.8k Golang : Web routing/multiplex example
+4.3k Javascript : Detect when console is activated and do something about it
+21.4k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+20.7k Golang : For loop continue,break and range
+22.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+14.8k Golang : Accurate and reliable decimal calculations
+8.4k Golang : Set or add headers for many or different handlers
+16.8k Golang : How to tell if a file is compressed either gzip or zip ?