使用GO库,emersion/go-imap(如有必要,使用go-message)如何获取整个原始消息,以便可以写入text/eml文件?

最佳答案

最终,我找到了如何获取整个原始消息。
这是我的代码,以防他人

package main

import (
    "crypto/tls"
    "github.com/emersion/go-imap"
    "github.com/emersion/go-imap/client"
    "log"
)

func main() {

    useStartTLS := true
    host := "mail.example.com"
    port := "143"
    uname := "yourusername"
    upass := "yoursecretpassword"

    hostport := host + ":" + port

    log.Println("Using host and port:-", hostport)
    log.Println("With User:-", uname)
    log.Println("Connecting to server...")

    // Connect to server
    c, err := client.Dial(hostport)

    //c.SetDebug(os.Stdout)

    if err != nil {
        log.Fatal(err)
    }
    log.Println("Connected")

    // Don't forget to logout
    defer c.Logout()

    if useStartTLS == true {

        ret, err := c.SupportStartTLS()
        if err != nil {
            log.Println("Error trying to determine whether StartTLS is supported.")
            log.Fatal(err)
        }

        if ret == false {
            log.Println("StartTLS is not supported.")
            log.Fatal(err)
        }

        log.Println("Good, StartTLS is supported.")

        // Start a TLS session
        tlsConfig := &tls.Config{ServerName: host}
        if err := c.StartTLS(tlsConfig); err != nil {
            log.Fatal(err)
        }
        log.Println("TLS started")
    }

    // Login
    if err := c.Login(uname, upass); err != nil {
        log.Fatal(err)
    }
    log.Println("Logged in")


    log.Println("Getting Last Message")

    // Select INBOX
    mbox, err := c.Select("INBOX", false)
    if err != nil {
        log.Fatal(err)
    }

    if mbox.Messages == 0 {
        log.Fatal("No message in mailbox")
    }

    // Get the last message
    seqset := new(imap.SeqSet)
    seqset.AddNum(mbox.Messages)  //since mbox.Messages is total number, this gets last

    // Get the whole message RAW
    items := []imap.FetchItem{imap.FetchRFC822,}

    messages := make(chan *imap.Message, 1)
    go func() {
        if err := c.Fetch(seqset, items, messages); err != nil {
            log.Fatal(err)
        }
    }()

    msg := <-messages
    if msg == nil {
        log.Fatal("Server didn't returned message")
    }

    for _, value := range msg.Body {
        len := value.Len()
        buf := make([]byte, len)
        n, err := value.Read(buf)
        if err != nil {
            log.Fatal(err)
        }
        if n != len {
            log.Fatal("Didn't read correct length")
        }
        println("+++++++++++++++++++++++Start of Raw Message +++++++++++++++++++++++++++++++")
        print(string(buf))
        println("+++++++++++++++++++++++End of Raw Message +++++++++++++++++++++++++++++++++")
    }

    log.Println("Done")
}

关于go - 从emersion/go-imap获取原始消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52871478/

10-17 01:38