Как получать вложения файлов из Mailgun в Go - PullRequest
0 голосов
/ 29 ноября 2018

Я пытаюсь выяснить, как получать вложения файлов для электронной почты из почтового пистолета с golang.Они предоставляют только пример Python https://documentation.mailgun.com/en/latest/quickstart-receiving.html:

# Handler for HTTP POST to http://myhost.com/messages for the route defined above
def on_incoming_message(request):
     if request.method == 'POST':
         sender    = request.POST.get('sender')
         recipient = request.POST.get('recipient')
         subject   = request.POST.get('subject', '')

         body_plain = request.POST.get('body-plain', '')
         body_without_quotes = request.POST.get('stripped-text', '')
         # note: other MIME headers are also posted here...

         # attachments:
         for key in request.FILES:
             file = request.FILES[key]
             # do something with the file

     # Returned text is ignored but HTTP status code matters:
     # Mailgun wants to see 2xx, otherwise it will make another attempt in 5 minutes
     return HttpResponse('OK')

Как мне обрабатывать эту часть в Go, или какого типа это «файлы»?

# attachments:
         for key in request.FILES:
             file = request.FILES[key]

1 Ответ

0 голосов
/ 29 ноября 2018

Mailgun может отправлять образцы запросов на обратные вызовы в настройках маршрутизации для вашего домена: https://app.mailgun.com/app/routes. Для быстрого просмотра создайте корзину на http://bin.mailgun.net и введите этот URL.

Вы увидите, что запросы на "переадресацию" действий содержат тела multipart / form-data, поэтому вы используете http.Request.FormFile для доступа к вложениям:

http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
    // r.FormFile and r.FormValue will call ParseMultipartForm
    // automatically if necessary, but they ignore any errors. For
    // robustness we do it ourselves.
    if err := r.ParseMultipartForm(10 << 20); err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    // The "attachment-count" field reports how many attachments there are.
    n, _ := strconv.Atoi(r.FormValue("attachment-count"))

    // The file fields are then named "attachment-1", "attachment-2", ..., "attachment-n".
    for i := 1; i <= n; i++ {
        fieldName := fmt.Sprintf("attachment-%d", i)
        file, header, err := r.FormFile(fieldName)
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }

        fmt.Printf("%s (%d bytes)\n", header.Filename, header.Size)

        var _ = file // call file.Read() to read the file contents
    }
})

ДляТестовая полезная нагрузка Mailgun будет иметь следующий результат:

crabby.gif (2785 bytes)
attached_файл.txt (32 bytes)
...