Skip to content

Instantly share code, notes, and snippets.

@dev-jaydeep
Last active December 7, 2021 09:53
Show Gist options
  • Save dev-jaydeep/abd48f34a8878c029a14158440fe4a10 to your computer and use it in GitHub Desktop.
Save dev-jaydeep/abd48f34a8878c029a14158440fe4a10 to your computer and use it in GitHub Desktop.
send an email with attachment using mailgun api
<?php
define('MAILGUN_URL', 'https://api.mailgun.net/v3/{{DOMAIN}}');
define('MAILGUN_KEY', '{{APIKEY}');
/**
* @param $to - a@xyz.com or a@xyz.com, b@xyz.com
* @param $from - doe <doe@xyz.com>
* @param $subject - subject
* @param $html - rich body
* @param $text - text body
* @param $reply_to - doe <doe@xyz.com>
* @param $bcc - doe <doe@xyz.com>
* @param $attachments- array of attachment
*/
function send($to, $from, $subject, $html, $text = null, $reply_to = null, $bcc = null, $attachments = [])
{
if (is_array($to)) {
$to = implode(',', $to);
} else {
$to = $to;
}
$array_data = [
'from' => $from,
'to' => $to,
'subject' => $subject,
'html' => $html,
'text' => $text,
'o:tracking' => 'yes',
'o:tracking-clicks' => 'yes',
'o:tracking-opens' => 'yes',
];
if ($reply_to) {
$array_data['h:Reply-To'] = $reply_to;
}
if ($bcc) {
$array_data['bcc'] = $bcc;
}
$index = 1;
foreach ($attachments as $attachment) {
if (file_exists($attachment)) {
$array_data['attachment[' . $index . ']'] = curl_file_create($attachment, mime_content_type($attachment), basename($attachment));
$index++;
}
}
$ch = curl_init(MAILGUN_URL . '/messages');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:' . MAILGUN_KEY);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$results = json_decode($response, true);
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment