Mailgun Sent mail With attachment
Asked Answered
T

9

12

I am facing issue when mail having attachment sent using mailgun. If anyone has done this thing please reply. This is my code...

$mg_api = 'key-3ax6xnjp29jd6fds4gc373sgvjxteol0';
$mg_version = 'api.mailgun.net/v2/';
$mg_domain = "samples.mailgun.org";
$mg_from_email = "[email protected]";
$mg_reply_to_email = "[email protected]";

$mg_message_url = "https://".$mg_version.$mg_domain."/messages";


$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

curl_setopt ($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_VERBOSE, 0);
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $mg_api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, true); 
//curl_setopt($curl, CURLOPT_POSTFIELDS, $params); 
curl_setopt($ch, CURLOPT_HEADER, false); 

//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, $mg_message_url);
curl_setopt($ch, CURLOPT_POSTFIELDS,                
        array(  'from'      => 'aaaa <' . '[email protected]' . '>',
                'to'        => '[email protected]',
                'h:Reply-To'=>  ' <' . $mg_reply_to_email . '>',
                'subject'   => 'aaaaa'.time(),
                'html'      => 'aaaaaa',
                'attachment'[1] => 'aaa.rar'
            ));
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result,TRUE);
print_r($res);

(I have used my mailgun settings)

I receive the email without the attachment. If I use the URL path it displays the URL instead of the attachment.

Tarry answered 9/1, 2013 at 6:42 Comment(0)
M
7

You need to change the last parameter in the following way: attachment[1]' => '@aaa.rar

We have some samples in our documentation for this use case. Just click PHP in the top bar to switch the language. http://documentation.mailgun.net/user_manual.html#examples-sending-messages-via-http

Please don't hesitate to send us an email with any questions to [email protected]. We are always happy to help.

Mulkey answered 9/1, 2013 at 18:13 Comment(3)
your examples require composerFidelafidelas
@Mulkey can attachment be direct link instead of local file? for example like attachment[1]' => '@http://example.com/direc/file/path/file.jpg ?Dremadremann
By the way, the mailgun doc link above doesn't work because Mailgun didn't redirect .net links to .com, lol... this link works: documentation.mailgun.com/user_manual.html#sending-via-apiApocopate
A
9

I realise this is old but I've just run into this problem and this page is pretty much the only info I can find on the net. So I hope this will assist someone else. After talking to MailGun support I've found the following works with the current API.

Cycles through an array of zero to n attachment files:

    $attachmentsArray = array('file1.txt', 'file2.txt');
    $x = 1;
    foreach( $attachmentsArray as $att )
    {
        $msgArray["attachment[$x]"] = curl_file_create( $att );
        $x ++;
    }

    // relevant cURL parameter, $msgArray also contains to, from, subject  parameters etc.
    curl_setopt($ch, CURLOPT_POSTFIELDS,$msgArray);
Aimless answered 16/3, 2016 at 7:6 Comment(2)
To clarify, this example is NOT using composer as is required for the MailGun SDK, this is accessing the MailGun API via PHP/cURLAimless
This requires PHP 5.5 or higher (hence the reason why it hasn't been brought up as a solution before).Autotype
M
7

You need to change the last parameter in the following way: attachment[1]' => '@aaa.rar

We have some samples in our documentation for this use case. Just click PHP in the top bar to switch the language. http://documentation.mailgun.net/user_manual.html#examples-sending-messages-via-http

Please don't hesitate to send us an email with any questions to [email protected]. We are always happy to help.

Mulkey answered 9/1, 2013 at 18:13 Comment(3)
your examples require composerFidelafidelas
@Mulkey can attachment be direct link instead of local file? for example like attachment[1]' => '@http://example.com/direc/file/path/file.jpg ?Dremadremann
By the way, the mailgun doc link above doesn't work because Mailgun didn't redirect .net links to .com, lol... this link works: documentation.mailgun.com/user_manual.html#sending-via-apiApocopate
M
4

The documentation doesn't say it explicitly, but the attachment itself is bundled into the request as multipart/form-data.

The best way to debug what's going on is use Fiddler to watch the request. Make sure you accept Fiddler's root certificate, or the request won't issue due to the SSL error.

What you should see in Fiddler is for Headers:

Cookies / Login

Authorization: Basic <snip>==

Entity

Content-Type: multipart/form-data; boundary=<num>

And for TextView:

Content-Disposition: form-data; name="attachment"
@Test.pdf

Content-Disposition: form-data; name="attachment"; filename="Test.pdf"
Content-Type: application/pdf
<data>

Note that you POST the field 'attachment=@<filename>'. For form-data, the field name is also 'attachment', then has 'filename=<filename>' (without the '@') and finally the file contents.

I think CURL is supposed to just do this all for you magically based on using the '@' syntax and specifying a path to a file on your local machine. But without knowing the magic behavior it's hard to grok what's really happening.

For example, in C# it looks like this:

public static void SendMail(MailMessage message) {
    RestClient client = new RestClient();
    client.BaseUrl = apiUrl;
    client.Authenticator = new HttpBasicAuthenticator("api", apiKey);

    RestRequest request = new RestRequest();
    request.AddParameter("domain", domain, ParameterType.UrlSegment);
    request.Resource = "{domain}/messages";
    request.AddParameter("from", message.From.ToString());
    request.AddParameter("to", message.To[0].Address);
    request.AddParameter("subject", message.Subject);
    request.AddParameter("html", message.Body);

    foreach (Attachment attach in message.Attachments)
    {
        request.AddParameter("attachment", "@" + attach.Name);
        request.AddFile("attachment",
            attach.ContentStream.WriteTo,
            attach.Name,
            attach.ContentType.MediaType);
    }

    ...
    request.Method = Method.POST;
    IRestResponse response = client.Execute(request);
}
Myles answered 21/3, 2013 at 4:57 Comment(1)
hey have you ever used mailgun web api ..I am facing a bit problem in sending attachment using web apiFilicide
W
3

I got stuck on this issue for a while and the answers here helped me, but there is something I came across which is not mentioned yet.

I had been sending my POST parameters with a blank/NULL 'cc' value, such as: $post_data['cc'] = NULL;. This did not prevent me from sending text emails (no attachment), but it did cause problems when sending an email with an attachment. Removing the blank cc from my array resolved part of the issue.

Additionally I had been using http_build_query before posting my data via PHP curl and that prevented my email with attachment from being sent successfully.

Removing the empty cc and http_build_query resolved this for me. Maybe an uncommon case, but posting in case it is helpful for someone who has the same issue.

Whinchat answered 15/1, 2017 at 21:43 Comment(1)
Just verified the crash with mailgun api Aug. 8 2020, when using hhtp_build_query: just don't use it!Rest
P
0

Add attachment file:

"attachment[1]" = "@$_FILES['careerDocument']['tmp_name'];filename=test.jpg".
($contentType ? ';type=' . $contentType : '' ) ;
curl_setopt($ch, CURLOPT_POSTFIELDS, ($message));
Perishable answered 11/5, 2016 at 12:2 Comment(0)
S
0

Thsi worked for me:

<?php

$filePath='@Wealth_AC_AMF.pdf';

$curl_post_data=array(
    'from'    => 'Excited User <[email protected]>',
    'to'      => '[email protected]',
    'subject' => 'Hello',
    'text'    => 'test',
'attachment[1]' => $filePath
);

$service_url = 'https://api.mailgun.net/v3/test.com/messages';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:key-test"); 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 


$curl_response = curl_exec($curl);  
$response = json_decode($curl_response);
curl_close($curl);

var_dump($response);



 ?>
Stressful answered 24/6, 2016 at 7:2 Comment(1)
...and you can extend your array: 'attachment[2]' => $filePath2, etc.Rest
Q
0

This worked for me...

class Email {

    function send($array, $file_array) {
        $mgClient = new Mailgun('YOUR_MAILGUN_API_KEY');
        $domain = "mg.YOUR_DOMAIN.com";
        $result = $mgClient->sendMessage($domain, $array, array('attachment' => $file_array));
        return $result;
    }   
}

$array = array(
    'from'    => 'From <[email protected]>',
    'to'      => 'To <[email protected]>',
    'subject' => 'Your Subject',
    'html'    => '<h1>Hooray!</h1>',
);

$file_array = array('/var/www/scripts/test.csv');
echo json_encode($Email::send($array, $file_array));
Quicksand answered 30/3, 2018 at 15:42 Comment(0)
T
0

This is working fine for me.

require '../../vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('key-b0e955');
$domain = "domain.com";

# Make the call to the client.
$result = $mgClient->sendMessage("$domain",
  array('from'    => '<[email protected]>',
        'to'      => '<[email protected]>',
        'subject' => 'csv file',
        'text' => 'csv test file'
       ),array('attachment' => [
    ['remoteName'=>'student.csv', 'filePath'=>'/form/stu.csv']
  ]) );
Tactics answered 10/4, 2018 at 7:24 Comment(0)
E
0

This works for me. I have passed the attachment file URL in the attachment array. now I can send multiple attachments in email.

$attachment = [ 0 => 'https://www.crm.truerater.com/public/assets/client_upload_images/1634327873.png', 1 => 'https://www.crm.truerater.com/public/assets/client_upload_images/1634327873.png' ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/truerater.com/messages');
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    $post = array(
        'from' =>  $mailfromname .'<'.$mailfrom.'>',
        'to' => $toname.'<'.$to.'>',
        'cc' => '',
        'bcc' => '',
        'subject' => $subject,
        'html'=>$html,
        'text'=>$text,
        'o:tracking'=>'yes',
        'o:tracking-clicks'=>'yes',
        'o:tracking-opens'=>'yes',
        'o:tag'=>$tag,
        'h:Reply-To'=>$replyto,
    );
    if(sizeOf($attachment) > 0){
        $i=0;
        foreach ($attachment as $attach){
            $attachPath = substr($attach, strrpos($attach, '/public/') + 1);
            $post['attachment['.$i.']'] = curl_file_create($attach, '', substr($attachPath, strrpos($attachPath, '/') + 1));
            $i=$i+1;
        }
    }
    $headers_arr = array("Content-Type:multipart/form-data");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_USERPWD, 'api' . ':' . $key);
    curl_setopt($ch, CURLOPT_HEADER, $headers_arr);
    curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $result = curl_exec($ch);
    
    
    if (curl_errno($ch)) {
        $result = curl_error($ch);
        \Log::info($result);
    }
    else{
        $result = json_decode($result,true);
    }
    curl_close($ch);
   
    \Log::info($result);
    return $result;
Elexa answered 29/12, 2021 at 21:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.