Coding Notes

Send Email Attachments With MailJet

I didn’t use the mailjet wrapper, instead I used curl to call the request. Here’s an example code to send a pdf attachment file with mailjet. I believe its similar to the code in their documentation.

function sendMailjetAttachment($email = '', $name = '', $subject = '', $message = '', $file = '') {
  $mailjetApiKey = '';
  $mailjetApiSecret = '';
  $pdfBase64 = base64_encode(file_get_contents($file));
  
  $data = [
    'Messages' => [
      [
        'From' => [
          'Email' => "[email protected]",
          'Name' => "From Email"
        ],
        'To' => [
          [
            'Email' => $email,
            'Name' => $name
          ]
        ],
        'Subject' => $subject,
        'TextPart' => $message,
        'Attachments' => [
          [
            'ContentType' => "application/pdf",
            'Filename' => "sample.pdf",
            'Base64Content' =>  $pdfBase64
          ]
        ]
      ]
    ]
  ];      

  $dataString = json_encode($data);
  $ch = curl_init('https://api.mailjet.com/v3.1/send');

  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
  curl_setopt($ch, CURLOPT_USERPWD, "{$mailjetApiKey}:{$mailjetApiSecret}");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($dataString))
  );

  $response = json_decode(curl_exec($ch));
  
  print_r($response);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.