How to fetch the email body in go ( with imap ) ?. So far I could find the headers but there is no indication where to look for the body.
Send a FETCH command for the BODY[]
or BODY.PEEK[]
attributes.
For more information, see the IMAP spec.
I figured out how to get the body text. Here is the code:
c.Select("INBOX", true)
//fmt.Print("
Mailbox status:
", c.Mailbox)
// Fetch the headers of the 10 most recent messages
set, _ := imap.NewSeqSet("4:*")
//if c.Mailbox.Messages >= 10 {
// set.AddRange(c.Mailbox.Messages-9, c.Mailbox.Messages)
//} else {
// set.Add("1:*")
//}
cmd, _ = c.UIDFetch(set, "RFC822.HEADER", "RFC822.TEXT")
// Process responses while the command is running
fmt.Println("
Most 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
}
I had similar trouble. I found this example command for use "Fetch" and "Uid".
$ UID FETCH uid (body[text])
and my C# code example
string fileBody = ReceiveResponse($"$ UID FETCH {uidList[i]} (body[text])
");