Erlang hackney:使用附件在mailgun.com发送邮件

时间:2016-03-10 20:33:16

标签: erlang mailgun

我正在尝试使用hackney通过mailgun.com发送电子邮件,我在发送附件时遇到了一些问题(需要多部分)。

https://documentation.mailgun.com/api-sending.html#sending

基本上我的兴趣领域是:

from
to
subject
text
attachment File attachment. You can post multiple attachment values. Important: You must use multipart/form-data encoding when sending attachments.

我尝试了以下内容:

PayloadBase =[
   {<<"from">>, From},
   {<<"to">>, To},
   {<<"subject">>, Subject},
   {<<"text">>, TextBody},
   {<<"html">>, HtmlBody}
],

Payload = case Attachment of
    null ->
       {form, PayloadBase};
    _->
       {multipart, PayloadBase ++ [{file, Attachment}]}
end,

但由于某种原因,附件未发送..其他所有内容均按预期工作。 我不知道如何根据mailgun的要求将归档名称设置为“附件”..这就是我怀疑的错误

2 个答案:

答案 0 :(得分:0)

我还没有使用过mailgun,但我相信您需要将attachment作为字段名称。请参阅您发布的examples at the bottom of the page

curl -s --user 'api:YOUR_API_KEY' \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
    -F from='Excited User <YOU@YOUR_DOMAIN_NAME>' \
    -F to='foo@example.com' \
    -F cc='bar@example.com' \
    -F bcc='baz@example.com' \
    -F subject='Hello' \
    -F text='Testing some Mailgun awesomness!' \
    --form-string html='<html>HTML version of the body</html>' \
    -F attachment=@files/cartman.jpg \
    -F attachment=@files/cartman.png

如果您首先使用curl,然后可以debug what headers curl sends到服务器,则会更容易。然后你可以在Erlang中模仿它。

这篇文章解释what multipart/form-data is并指向W3 document,它提供了如何编码数据的示例。

答案 1 :(得分:0)

以下代码将解决问题:

Payload2 = case Attachment of
    null ->
        {form, PayloadBase};
    _->
        FName = hackney_bstr:to_binary(filename:basename(Attachment)),
        MyName = <<"attachment">>,
        Disposition = {<<"form-data">>, [{<<"name">>, <<"\"", MyName/binary, "\"">>}, {<<"filename">>, <<"\"", FName/binary, "\"">>}]},
        ExtraHeaders = [],
        {multipart, PayloadBase ++ [{file, Attachment, Disposition, ExtraHeaders}]}
end,

西尔维乌