Skip to content

Instantly share code, notes, and snippets.

@sakydev
Last active September 3, 2021 09:30
Show Gist options
  • Save sakydev/76f8fc259a2f19d56501e57ccfb93549 to your computer and use it in GitHub Desktop.
Save sakydev/76f8fc259a2f19d56501e57ccfb93549 to your computer and use it in GitHub Desktop.
php+mailgun: send email with mailgun php sdk
<?php
// requires Mailgun PHP SDK https://github.com/mailgun/mailgun-php
require 'vendor/autoload.php';
use Mailgun\Mailgun;
function sendMail($params) {
    $from = isset($params['from']) ? $params['from'] : 'name@default.com';
    $mailParams = array();
    $attachments = array();
    $mailParams['from'] = $params['sender_name'] . " <$from>";
    $mailParams['to'] = $params['to'];
    if (isset($params['attachment'])) {
        $attachments[] = array('filePath' => $params['attachment']['path'], 'filename' => $params['attachment']['name']);
        pr($attachments);
    }
    if (isset($params['custom_attachment'])) {
        foreach ($params['custom_attachment'] as $key => $file) {
            $m->addAttachmentFromFile($file['name'], $file['path']);
            $attachments[] = array('filePath' => $file['path'], 'filename' => $file['name']);
        }
    }
    if (isset($params['replyTo'])) {
        if (is_array($params['replyTo'])) {
            foreach ($params['replyTo'] as $key => $email) {
                $mailParams['h:Reply-To'][] = $email;
            }
        } else {
            $mailParams['h:Reply-To'] = $params['replyTo'];
        }
    }
    $mailParams['subject'] = $params['subject'];
    $isHtml = $params['message'] != strip_tags($params['message']);
    if ($isHtml) {
        $mailParams['html'] = $params['message'];
    } else {
        $mailParams['text'] = $params['message'];
    }
    if (!empty($attachments)) {
        $mailParams['attachment'] = $attachments;
    }
    $mg = Mailgun::create('mailgun_api_key');
    $mg->messages()->send('mailgun_domain', $mailParams);
}
$params = array();
$params['to'] = 'sendto@gmail.com';
$params['from'] = 'from@gmail.com';
$params['sender_name'] = 'Jon Snow';
$params['subject'] = 'THIS IS THE SUBJECT';
$params['message'] = 'Well, hello there';
$params['replyTo'] = 'tested@snow.com';
$params['attachment'] = array('path' => 'file.pdf', 'name' => 'file.pdf');
sendMail($params);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment