简体   繁体   中英

How to fetch body from imap server in Go

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?

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM