如何编写mbox格式的文件?

I have obtained the mail content and the necessary headers using Gmail API. I want to write those into mbox files. I could find Go packages and samples to read and parse mbox files. But how to create and write mbox file using Go?

The mbox file format (Wikipedia) is actually super-simple.

Each mail has a first line that starts "From ". Any first line in the email body that happens to start with "From " has either " " or ">" prepended. After each mail body, there's an extra blank line inserted. Typically, a mail header already has a "From ..." first line, so what you need to do is "iterate through each email, print it, scan the body to ensure all lines that start "From " have an escape, then finish each mail with a blank line".

Something like the following (will need adapting to how you represent emails):

package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

type Mail struct {
    Headers []string
    Body    []string
}

func (m *Mail) Save(w io.Writer) {
    for _, h := range m.Headers {
        fmt.Fprintln(w, h)
    }
    fmt.Println("")
    for _, b := range m.Body {
        if strings.HasPrefix(b, "From ") {
            fmt.Fprintln(w, ">", b)
        } else {
            fmt.Fprintln(w, b)
        }
    }
}

func WriteMbox(w io.Writer, mails []Mail) {
    for _, m := range mails {
        m.Save(w)
        fmt.Fprintln(w, "")
    }
}

func main() {
    m := Mail{Headers: []string{"From test", "Subject: Test"}, 
              Body: []string{"Mail body, totes, like"}}
    WriteMbox(os.Stdout, []Mail{m, m, m})
}