0

I'm trying to send an email via mailgun.com using the hackney and I have some issues sending attachments (which requires multipart).

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

Basically my interest fields are:

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

I tried the following:

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

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

But for some reason the attachment is not sent.. Everything else works as expected. I don't see how I can set the filed name to "attachment" as required by mailgun .. at this this is what I suspect beeing wrong

silviu
  • 179
  • 3
  • 10

2 Answers2

0

I haven't used mailgun but I believe that you would need to put attachment as the field name. See examples at the bottom of the page you posted:

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

It will be easier if you make it working with curl first, then you can debug what headers curl sends to the server. And then you can mimic that in Erlang.

This post explains what multipart/form-data is and points to the W3 document that provides examples how the data should be encoded.

Community
  • 1
  • 1
Greg
  • 8,230
  • 5
  • 38
  • 53
  • with curl is properly working. but with hackeny I'm not able to make it work. I tried also {multipart, PayloadBase ++ [{file, Attachment, [{<<"name">>, <<"attachment">>}]}]}. but no luck. – silviu Mar 11 '16 at 12:14
  • Yeah, I am sure that both, the API and curl work fine. I mentioned curl so that you can debug what headers should be send and fix your code, not to check if it works. – Greg Mar 11 '16 at 14:59
0

The following code will fix the problem:

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,

Silviu

silviu
  • 179
  • 3
  • 10