A
A
Anton2020-12-09 20:43:53
go
Anton, 2020-12-09 20:43:53

How to get file from email in GoLang?

Tell me, if there is an example of collecting all attachments from the mail for (I looked here for github.com/emersion/go-imap, but could not implement - How to download a letter and an attachment using golang imap ?. I did not understand how to form "p.Header.( type)").
Or maybe someone did something similar. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-12-09
@anton11122211

package main

import (
    "io"
    "io/ioutil"
    "log"

    "github.com/emersion/go-imap"
    "github.com/emersion/go-imap/client"
    "github.com/emersion/go-message"
)

func main() {
    log.Println("Connecting to server...")

    c, err := client.DialTLS("xxxxxxxxx", nil)
    if err != nil {
        log.Fatal(err)
    }

    log.Println("Connected")

    defer c.Logout()

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

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

    seqset := new(imap.SeqSet)
    seqset.AddRange(1, mbox.Messages)

    messages := make(chan *imap.Message, 10)
    done := make(chan error, 1)
    go func() {
        done <- c.Fetch(seqset, []imap.FetchItem{imap.FetchRFC822}, messages)
    }()

    for msg := range messages {
        for _, r := range msg.Body {
            entity, err := message.Read(r)
            if err != nil {
                log.Fatal(err)
            }

            multiPartReader := entity.MultipartReader()

            for e, err := multiPartReader.NextPart(); err != io.EOF; e, err = multiPartReader.NextPart() {
                kind, params, cErr := e.Header.ContentType()
                if cErr != nil {
                    log.Fatal(cErr)
                }

                if kind != "image/png" && kind != "image/gif" {
                    continue
                }

                c, rErr := ioutil.ReadAll(e.Body)
                if rErr != nil {
                    log.Fatal(rErr)
                }

                log.Printf("Dump file %s", params["name"])

                if fErr := ioutil.WriteFile("/tmp/"+params["name"], c, 0777); ferr != nil {
                    log.Fatal(fErr)
                }
            }
        }
    }

    if err := <-done; err != nil {
        log.Fatal(err)
    }

    log.Println("Done")
}

An example was taken here https://stackoverflow.com/questions/55203878/how-t...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question