Standard library / net/mail

mail.ReadMessage()

Parse message headers and expose the remaining body as a reader. It does not decode MIME attachments or transfer encoding. Expected stdout: 'demo hello\n'.

Formal Syntax & Structure

go syntaxgo
func ReadMessage(r io.Reader) (msg *Message, err error)

Parameters & Attributes

NameTypeDescription
rio.ReaderInput stream containing message headers and body. Bound untrusted input.

Return Value

(msg *Message, err error)

Message with parsed headers and body reader, or error.

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/mail"  "strings")
func main() {  m := must(mail.ReadMessage(strings.NewReader("From: Ada <ada@example.invalid>\r\nSubject: demo\r\nDate: Tue, 02 Jan 2024 03:04:05 +0000\r\n\r\nhello")))  fmt.Println(m.Header.Get("Subject"), string(must(io.ReadAll(m.Body))))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference