亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號