Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch body from imap server in Go

Tags:

go

fetch

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?

like image 770
Qian Chen Avatar asked Jan 06 '15 03:01

Qian Chen


2 Answers

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
}
like image 172
Qian Chen Avatar answered Oct 13 '22 22:10

Qian Chen


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.

like image 33
James Henstridge Avatar answered Oct 13 '22 23:10

James Henstridge