我正在尝试找出如何使用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]
答案 0 :(得分:1)
您可以让Mailgun在您的域的路由设置中发送对回调的样本请求:https://app.mailgun.com/app/routes。要快速浏览,请在http://bin.mailgun.net上创建一个bin,然后输入该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)