如何在 Go 中从 Mailgun 接收文件附件

How to receive file attachments from Mailgun in Go

我正在尝试了解如何使用 golang 从 mailgun 接收电子邮件的文件附件。他们仅提供 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 中处理这部分,或者这个 'files' 是什么类型?

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

您可以让 Mailgun 在您域的路由设置中发送回调请求示例:https://app.mailgun.com/app/routes. For a quick overview, create a bin on http://bin.mailgun.net 并输入 URL。

您将看到 "forward" 操作的请求包含 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)