英文:
How to fetch body from imap server in Go
问题
我成功地使用这个网址上的示例代码(https://godoc.org/code.google.com/p/go-imap/go1/imap#example-Client)获取了一份电子邮件头列表。然而,我仍然无法获取电子邮件的正文内容。有人可以展示一些能够从 Golang 中的 IMAP 服务器获取电子邮件正文的工作示例代码吗?
英文:
I successfully fetched a list of email headers using the sample code from this url: https://godoc.org/code.google.com/p/go-imap/go1/imap#example-Client . However, I still haven't been able to fetch the body of the emails. Can anyone show some working sample code that could fetch the body of the emails from a imap server in Golang?
答案1
得分: 3
我现在知道如何获取正文文本了。
cmd, _ = c.UIDFetch(set, "RFC822.HEADER", "RFC822.TEXT")
// 在命令运行时处理响应
fmt.Println("\n最近的消息:")
for cmd.InProgress() {
    // 等待下一个响应(无超时)
    c.Recv(-1)
    // 处理命令数据
    for _, rsp = range cmd.Data {
        header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
        uid := imap.AsNumber((rsp.MessageInfo().Attrs["UID"]))
        body := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.TEXT"])
        if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
            fmt.Println("|--", msg.Header.Get("Subject"))
            fmt.Println("UID: ", uid)
            fmt.Println(string(body))
        }
    }
    cmd.Data = nil
    c.Data = nil
}
英文:
I figured out how to get the body text now.
cmd, _ = c.UIDFetch(set, "RFC822.HEADER", "RFC822.TEXT")
// Process responses while the command is running
fmt.Println("\nMost recent messages:")
for cmd.InProgress() {
	// Wait for the next response (no timeout)
	c.Recv(-1)
	// Process command data
	for _, rsp = range cmd.Data {
		header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
		uid := imap.AsNumber((rsp.MessageInfo().Attrs["UID"]))
		body := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.TEXT"])
		if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
			fmt.Println("|--", msg.Header.Get("Subject"))
			fmt.Println("UID: ", uid)
			fmt.Println(string(body))
		}
	}
	cmd.Data = nil
	c.Data = nil
}
答案2
得分: 1
你提供的示例代码演示了使用IMAP的FETCH命令来获取消息的RFC822.HEADER数据项。RFC中列出了可以从消息中获取的标准数据项的列表。
如果你想要获取整个MIME格式的消息(包括头部和正文),那么请求BODY应该就可以了。你可以通过请求BODY[HEADER]和BODY[TEXT]来分别获取头部和消息正文。修改示例程序以使用其中一个数据项,就可以获取你想要的数据。
英文:
The example code you've linked to demonstrates the use of the IMAP FETCH command to fetch the RFC822.HEADER message data item for a message.  The RFC contains a list of standard data items you can fetch from a message.
If you want the entire mime formatted message (both headers and body), then requesting BODY should do.  You can get the headers and message body separately by requesting BODY[HEADER] and BODY[TEXT] respectively.  Modifying the sample program to use one of these data items should get the data you are after.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论