8

I am trying to send a mail with attachments with mailgun. The mail itself is fine, but it is missing the attachment. Also in the mailgun log it shows up fine, but the attachment array is empty.

I replaced my credentials with example.com. The file is placed in a subdirectory and is readable.

$filename = 'directory/example.pdf';
$parameters = array('from' => 'Example <example@mail.example.com>',
                    'to' => 'example@example.com',
                    'subject' => 'Subject',
                    'text' => 'This is just a test.',
                    'attachment[1]' => '@' . $filename);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/mail.example.com/messages');
curl_setopt($ch, CURLOPT_USERPWD, 'api:key-ThisIsJustARandomString');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

I don't get an error, this is the $response:

string(103) "{
    "id": "<20170514122638.8820.55203.4543B111@mail.example.com>",
    "message": "Queued. Thank you."
}"

Within the mailgun logs no attachments are listed:

"message": {
    "headers": {
        "to": "example@example.com",
        "message-id": "20170514122638.8820.55203.4543B111@mail.example.com",
        "from": "Example <example@mail.example.com>",
        "subject": "Subject"
    },
    "attachments": [],
    "size": 349
},

According to all documentation I found this would be the correct solution, but it is not working.

Thanks in advance for all replies.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Vestalis
  • 270
  • 2
  • 4
  • 9

5 Answers5

16

Change your first code to:

$filename = 'directory/example.pdf';
$parameters = array('from' => 'Example <example@mail.example.com>',
                'to' => 'example@example.com',
                'subject' => 'Subject',
                'text' => 'This is just a test.',
                'attachment[1]' => curl_file_create($filename, 'application/pdf', 'example.pdf'));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/mail.example.com/messages');
curl_setopt($ch, CURLOPT_USERPWD, 'api:key-ThisIsJustARandomString');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

I changed '@'.$filename to curl_file_create($filename, 'application/pdf', 'example.pdf').

See documentation curl_file_create and check the notes for PHP < 5.5.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Phillip Plum
  • 537
  • 4
  • 14
4

or use the api https://documentation.mailgun.com/en/latest/api-sending.html#examples

once the domains and parameters are set you can then just use $result = $mgClient->messages()->send( $domain, $params );

ThurstonLevi
  • 664
  • 13
  • 34
3

This worked for me.

<?php
 $path = $filename;
 define('MAILGUN_URL', 'https://api.mailgun.net/v3/domainname'); 
 define('MAILGUN_KEY', 'private api key from mail gun');
 **function sendmailbymailgun**($to,$toname,$mailfromname,$mailfrom,$subject,
  $html,$text,$tag,$replyto, $path){

$array_data = array(
'from'=> $mailfromname .'<'.$mailfrom.'>',
'to'=>$toname.'<'.$to.'>',
'subject'=>$subject,
'html'=>$html,
'text'=>$text,
'o:tracking'=>'yes',
'o:tracking-clicks'=>'yes',
'o:tracking-opens'=>'yes',
'o:tag'=>$tag,
'h:Reply-To'=>$replyto,
 'attachment[0]' =>  curl_file_create(__dir__."\\".$path, 'application/pdf', $path),
 'attachment[1]' =>  curl_file_create(__dir__."\\".$path, 'application/pdf', "example.pdf")
);
$session = curl_init(MAILGUN_URL.'/messages');
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($session, CURLOPT_USERPWD, 'api:'.MAILGUN_KEY);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $array_data);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($session);
curl_close($session);
$results = json_decode($response, true);
return $results;
}

  //: call the function
  $res = sendmailbymailgun("example@yahoo.com","Recipeint Name", "Sender Name", "sender@example.com","Email subject","Email body. find two attachment","","tags", "no-reply@example.com", $path);
  echo "<pre>".print_r($res, true)."</pre>";  


?>
0
$dest = "filepath/test.pdf";
$result = $mgClient->messages()->send($domain,
            array('from'    => 'Tester <test@test.com>',
              'to'      => 'test@test02.com',
              'subject' => 'Testing',
              'html'    => '<h1>Normal Testing</h1>',
              'attachment' => array(
                array(
                    'filePath' => $dest,
                    'filename' => 'test.pdf'
                    )
                )
              ));

This code is worked properly for me.

  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '21 at 06:21
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;
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • 2
    On Stack Overflow, the **how** is important, but a great part of the quality level of the site comes from the fact that people go to great lengths to explain the **why**. While a _code-only_ answer get the person who asked the question past whatever hurdle they might be facing, it doesn't do them or future visitors much good in the long run. See [Is there any benefit in code-only answers?](https://meta.stackexchange.com/a/148274/183937) – Steve Dec 29 '21 at 20:40
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 29 '21 at 20:54