Skip to content

Instantly share code, notes, and snippets.

@jonaslejon
Last active July 31, 2021 21:29
Show Gist options
  • Save jonaslejon/e1599d28121294e94601 to your computer and use it in GitHub Desktop.
Save jonaslejon/e1599d28121294e94601 to your computer and use it in GitHub Desktop.
Send mail with Mailgun API version 2 and PHP. Should also work with version 3 of the Mailgun API
define("DOMAIN", "test.se");
define("MAILGUN_API", "XXX123"); // Mailgun Private API Key
function br2nl($string) {
return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
function mg_send($to, $subject, $message) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:'.MAILGUN_API);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$plain = strip_tags(br2nl($message));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v2/'.DOMAIN.'/messages');
curl_setopt($ch, CURLOPT_POSTFIELDS, array('from' => 'support@'.DOMAIN,
'to' => $to,
'subject' => $subject,
'html' => $message,
'text' => $plain));
$j = json_decode(curl_exec($ch));
$info = curl_getinfo($ch);
if($info['http_code'] != 200)
return false;
curl_close($ch);
return $j;
}
@BenMic
Copy link

BenMic commented Jun 1, 2017

Very useful. Works with Mailgun API v3.

@jonaslejon
Copy link
Author

Thanks for all the comments! The code has been updated to work better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment