Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mailgun - send mail with attachment

I am trying to send mail in symfony with attachment with the help of mailgun

I have referred this Question. And this Reference. But didn't helped me.

This is my function,

public function sendMail($to, $subject, $body, $attachment = null)
{
    $mgClient = new Mailgun($this->container->getParameter('mailgun_key'));
    $domain = $this->container->getParameter('mailgun_domain');
    $content = [
        'from' => $this->container->getParameter('mailgun_from'),
        'to' => 'tester <' . $to . '>',
        'subject' => $subject,
        'text' => $body
    ];
    if (!empty($attachment)) {
        $result = $mgClient->sendMessage("$domain", $content);
    } else {
        $result = $mgClient->sendMessage("$domain", $content, [
            'attachment[0]' => [$attachment]
        ]);
    }
    return $result;
}

In attachment, I'm passing the file path. i.e /home/mypc/Downloads/test.txt

But I'm receiving only blank mail. Attachment is not coming.

Where am I wrong? Please help.

like image 685
Keyur Avatar asked Oct 28 '25 11:10

Keyur


2 Answers

The mailgun attachments documentation has the following information:

Attachments

You may attach a file from memory or by a file path.

From file path

$mg->messages()->send('example.com', [
  'from'    => '[email protected]', 
  'to'      => '[email protected]', 
  'subject' => 'Test file path attachments', 
  'text'    => 'Test',
  'attachment' => [
    ['filePath'=>'/tmp/foo.jpg', 'filename'=>'test.jpg']
  ]
]);

From memory

// Some how load the file to memory
$binaryFile = '[Binary data]';

$mg->messages()->send('example.com', [
  'from'    => '[email protected]', 
  'to'      => '[email protected]', 
  'subject' => 'Test memory attachments', 
  'text'    => 'Test',
  'attachment' => [
    ['fileContent'=>$binaryFile, 'filename'=>'test.jpg']
  ]
]);

Inline attachments

$mg->messages()->send('example.com', [
  'from'    => '[email protected]', 
  'to'      => '[email protected]', 
  'subject' => 'Test inline attachments', 
  'text'    => 'Test',
  'inline' => [
    ['filePath'=>'/tmp/foo.jpg', 'filename'=>'test.jpg']
  ]
]);
like image 128
Jared Forth Avatar answered Oct 31 '25 00:10

Jared Forth


Please replace below code

$result = $mgClient->sendMessage("$domain", $content, [
      'attachment[0]' => [$attachment]
]);

With

$result = $mgClient->sendMessage("$domain", $content, array(
      'attachment' => array($attachment)
));

Eg.

$result = $mgClient->sendMessage("$domain", $content, array(
    'attachment' => array('/home/mypc/Downloads/test.txt')
));

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

like image 44
Gopal Joshi Avatar answered Oct 31 '25 02:10

Gopal Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!