How to fetch body from imap server in Go
Asked Answered
G

2

6

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?

Glinys answered 6/1, 2015 at 3:29 Comment(0)
G
3

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
}
Glinys answered 6/1, 2015 at 7:59 Comment(0)
I
1

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.

Induration answered 6/1, 2015 at 5:51 Comment(1)
Thanks James. Now I'm reading the RFC 3501 in order to gain more knowledge about the IMAP protocol. I'm still struggling to get the Go API work to fetch the body. Can you please show me some working code example that fetches the body of the mails. Thanks.Glinys

© 2022 - 2024 — McMap. All rights reserved.