You are here

function mailgun_send in Mailgun 7

Send an e-mail using the Mailgun API.

Parameters

array $mailgun_message: A Mailgun message array. Contains the following keys:

Return value

bool TRUE if the mail was successfully accepted, FALSE otherwise.

1 call to mailgun_send()
MailgunMailSystem::mail in ./mailgun.mail.inc
Send the e-mail message.
1 string reference to 'mailgun_send'
mailgun_cron_queue_info in ./mailgun.module
Implements hook_cron_queue_info().

File

./mailgun.module, line 291
Provides integration with Mailgun's email sending API.

Code

function mailgun_send(array $mailgun_message) {
  $client = mailgun_get_client();
  if (!$client) {
    return FALSE;
  }

  // Test mode. Mailgun will accept the message but will not send it.
  if (variable_get('mailgun_test', FALSE)) {
    $mailgun_message['o:testmode'] = 'yes';
  }

  // Merge the $mailgun_message array with options.
  $mailgun_message += $mailgun_message['params'];
  unset($mailgun_message['params']);
  if (variable_get('mailgun_domain', '_sender') === '_sender') {

    // Extract the domain from the sender's email address.
    // Use regular expression to check since it could be either a plain email
    // address or in the form "Name <example@example.com>".
    $tokens = preg_match('/^\\s*(.+?)\\s*<\\s*([^>]+)\\s*>$/', $mailgun_message['from'], $matches) === 1 ? explode('@', $matches[2]) : explode('@', $mailgun_message['from']);
    $mail_domain = array_pop($tokens);

    // Retrieve a list of available domains first.
    $domains = array();
    try {
      $result = $client
        ->domains()
        ->index();
      if (!empty($result)) {
        if ($result
          ->getTotalCount() > 100) {
          $result = $client
            ->domains()
            ->index($result
            ->getTotalCount());
        }
        foreach ($result
          ->getDomains() as $domain) {
          $domains[$domain
            ->getName()] = $domain
            ->getName();
        }
      }
      else {
        watchdog('mailgun', 'Could not retrieve domain list.', array(), WATCHDOG_ERROR);
      }
    } catch (Exception $e) {
      watchdog('mailgun', 'An exception occurred while retrieving domains. @code: @message', array(
        '@code' => $e
          ->getCode(),
        '@message' => $e
          ->getMessage(),
      ), WATCHDOG_ERROR);
    }
    if (empty($domains)) {

      // No domain available.
      // Although this shouldn't happen, doesn't hurt to check.
      return FALSE;
    }

    // Now, we need to get the working domain. This is generally the domain the
    // From address is on or the root domain of it.
    $working_domain = '';
    if (in_array($mail_domain, $domains, TRUE)) {

      // Great. Found it.
      $working_domain = $mail_domain;
    }
    else {

      // Oops. No match. Perhaps it's a subdomain instead.
      foreach ($domains as $domain) {
        if (strpos($domain, $mail_domain) !== FALSE) {

          // Got it.
          $working_domain = $domain;
          break;
        }
      }
    }

    // There is a chance that the user is attempting to send from an email
    // address that's on a domain not yet added to the Mailgun account.
    // In that case, abort sending and report error.
    if (empty($working_domain)) {
      watchdog('mailgun', 'Unable to locate a working domain for From address %mail. Aborting sending.', array(
        '%mail' => $mailgun_message['from'],
      ), WATCHDOG_ERROR);
      return FALSE;
    }
  }
  else {
    $working_domain = variable_get('mailgun_domain', '');
  }

  // Send message with attachments.
  if (!empty($mailgun_message['attachment'])) {
    foreach ($mailgun_message['attachment'] as &$attachment) {

      // Ignore array constructions. Not sure what values can be here.
      if (is_array($attachment)) {
        continue;
      }
      $attachment = array(
        'filePath' => $attachment,
      );
    }
  }
  try {
    $result = $client
      ->messages()
      ->send($working_domain, $mailgun_message);
    if (!empty($result)) {
      if (variable_get('mailgun_log', FALSE)) {
        watchdog('mailgun', 'Successfully sent message from %from to %to. %message.', array(
          '%from' => $mailgun_message['from'],
          '%to' => $mailgun_message['to'],
          '%message' => $result
            ->getMessage(),
        ));
      }
      return TRUE;
    }
    else {
      watchdog('mailgun', 'Failed to send message from %from to %to. %message.', array(
        '%from' => $mailgun_message['from'],
        '%to' => $mailgun_message['to'],
        '%message' => $result
          ->getMessage(),
      ), WATCHDOG_ERROR);
      return FALSE;
    }
  } catch (Exception $e) {
    watchdog('mailgun', 'Exception occurred while trying to send test email from %from to %to. @code: @message.', array(
      '%from' => $mailgun_message['from'],
      '%to' => $mailgun_message['to'],
      '@code' => $e
        ->getCode(),
      '@message' => $e
        ->getMessage(),
    ));
    return FALSE;
  }
}