英文:
How to write mbox-formatted files?
问题
我已经使用Gmail API获取了邮件内容和必要的标头。我想将它们写入mbox文件中。我找到了一些Go语言的包和示例来读取和解析mbox文件。但是如何使用Go语言创建和写入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?
答案1
得分: 5
mbox文件格式(维基百科)实际上非常简单。
每封邮件都有一行以"From "开头的首行。邮件正文中任何以"From "开头的首行都会在前面加上一个空格或">"。在每封邮件正文之后,会插入一个额外的空行。通常,邮件头部已经有一个"From ..."的首行,所以你需要做的是"遍历每封邮件,打印它,扫描正文以确保所有以"From "开头的行都有转义字符,然后在每封邮件的末尾加上一个空行"。
类似以下的代码(需要根据你表示邮件的方式进行适当调整):
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})
}
英文:
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})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论