为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
回首忆惘然 2023-05-15 10:14:32
我正在尝试找出如何使用 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 abovedef 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 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您可以让 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)


查看完整回答
反对 回复 2023-05-15
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信