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

我正在尝试找出如何使用 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 中处理这部分,或者这个“文件”是什么类型?


# attachments:

         for key in request.FILES:

             file = request.FILES[key]


回首忆惘然
浏览 112回答 1
1回答

慕侠2389804

您可以让 Mailgun 在您域的路由设置中发送回调请求示例: https:&nbsp;//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) {&nbsp; &nbsp; // r.FormFile and r.FormValue will call ParseMultipartForm&nbsp; &nbsp; // automatically if necessary, but they ignore any errors. For&nbsp; &nbsp; // robustness we do it ourselves.&nbsp; &nbsp; if err := r.ParseMultipartForm(10 << 20); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), 500)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; // The "attachment-count" field reports how many attachments there are.&nbsp; &nbsp; n, _ := strconv.Atoi(r.FormValue("attachment-count"))&nbsp; &nbsp; // The file fields are then named "attachment-1", "attachment-2", ..., "attachment-n".&nbsp; &nbsp; for i := 1; i <= n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fieldName := fmt.Sprintf("attachment-%d", i)&nbsp; &nbsp; &nbsp; &nbsp; file, header, err := r.FormFile(fieldName)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, err.Error(), 500)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s (%d bytes)\n", header.Filename, header.Size)&nbsp; &nbsp; &nbsp; &nbsp; var _ = file // call file.Read() to read the file contents&nbsp; &nbsp; }})对于 Mailgun 的测试负载,输出将是:crabby.gif (2785 bytes)attached_файл.txt (32 bytes)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go