You are here

public function MailgunHandler::sendMail in Mailgun 8

Connects to Mailgun API and sends out the email.

Parameters

array $mailgunMessage: A message array, as described in https://documentation.mailgun.com/en/latest/api-sending.html#sending.

Return value

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

Overrides MailgunHandlerInterface::sendMail

See also

https://documentation.mailgun.com/en/latest/api-sending.html#sending

File

src/MailgunHandler.php, line 79

Class

MailgunHandler
Mail handler to send out an email message array to the Mailgun API.

Namespace

Drupal\mailgun

Code

public function sendMail(array $mailgunMessage) {
  try {
    if (!$this
      ->validateMailgunApiSettings()) {
      $this->logger
        ->error('Failed to send message from %from to %to. Please check the Mailgun settings.', [
        '%from' => $mailgunMessage['from'],
        '%to' => $this
          ->getRecipients($mailgunMessage),
      ]);
      return FALSE;
    }
    $domain = $this
      ->getDomain($mailgunMessage['from']);
    if ($domain === FALSE) {
      $this->logger
        ->error('Failed to send message from %from to %to. Could not retrieve domain from sender info.', [
        '%from' => $mailgunMessage['from'],
        '%to' => $this
          ->getRecipients($mailgunMessage),
      ]);
      return FALSE;
    }
    $response = $this->mailgun
      ->messages()
      ->send($domain, $mailgunMessage);

    // Debug mode: log all messages.
    if ($this->mailgunConfig
      ->get('debug_mode')) {
      $this->logger
        ->notice('Successfully sent message from %from to %to. %id %message.', [
        '%from' => $mailgunMessage['from'],
        '%to' => $this
          ->getRecipients($mailgunMessage),
        '%id' => $response
          ->getId(),
        '%message' => $response
          ->getMessage(),
      ]);
    }
    return $response;
  } catch (Exception $e) {
    $this->logger
      ->error('Exception occurred while trying to send test email from %from to %to. Error code @code: @message', [
      '%from' => $mailgunMessage['from'],
      '%to' => $this
        ->getRecipients($mailgunMessage),
      '@code' => $e
        ->getCode(),
      '@message' => $e
        ->getMessage(),
    ]);
    return FALSE;
  }
}