You are here

class AmazonSes in Amazon SES 7.2

Modify the drupal mail system to use Amazon SES.

Hierarchy

Expanded class hierarchy of AmazonSes

File

src/AmazonSes.php, line 13
Class for interacting with Amazon SES service.

Namespace

Drupal\amazon_ses
View source
class AmazonSes {
  private $sesClient;

  /**
   * Initiliaze this class.
   */
  public function __construct($region, $key, $secret) {
    $this->sesClient = new \Aws\Ses\SesClient([
      'version' => 'latest',
      'region' => $region,
      'credentials' => [
        'key' => $key,
        'secret' => $secret,
      ],
    ]);
  }

  /**
   * Add required parameter & header to the Query according to Query action.
   */
  public function performServiceAction($query_action, $action_parameter = array()) {
    switch ($query_action) {
      case 'DeleteIdentity':
        $result = $this
          ->deleteIdentity($action_parameter);
        break;
      case 'GetIdentityDkimAttributes':
        $result = $this
          ->getIdentityDkimAttributes($action_parameter);
        break;
      case 'GetIdentityVerificationAttributes':
        $result = $this
          ->getIdentityVerificationAttributes($action_parameter);
        break;
      case 'GetSendStatistics':
        $result = $this
          ->getSendStatistics($action_parameter);
        break;
      case 'GetSendQuota':
        $result = $this
          ->getSendQuota($action_parameter);
        break;
      case 'ListIdentities':
        $result = $this
          ->listIdentities($action_parameter);
        break;
      case 'SendEmail':
        $result = $this
          ->sendEmail($action_parameter);
        break;
      case 'VerifyDomainIdentity':
        $result = $this
          ->verifyDomainIdentity($action_parameter);
        break;
      case 'VerifyEmailIdentity':
        $result = $this
          ->verifyEmailIdentity($action_parameter);
        break;
    }
    return $result;
  }

  /**
   * Call Query API action DeleteIdentity.
   *
   * Deletes the specified identity (email address or domain) from the list of
   * verified identities. This action is throttled at one request per second.
   */
  private function deleteIdentity($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->deleteIdentity([
        'Identity' => $action_parameter['identity'],
      ]);
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action GetIdentityNotificationAttributes.
   *
   * This action is throttled at one request per second.
   */
  private function getIdentityDkimAttributes($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->getIdentityDkimAttributes([
        'Identities' => $action_parameter['Identities'],
      ]);
      if (!empty($response['DkimAttributes'])) {
        foreach ($response['DkimAttributes'] as $key => $value) {
          $result['Identity'] = check_plain($key);
          $result['DkimEnabled'] = check_plain($value['DkimEnabled']);
          $result['DkimVerificationStatus'] = check_plain($value['DkimVerificationStatus']);
          $dkim_tokens = $value['DkimTokens'];

          // Prepare dkimTokens.
          if (strpos($result['Identity'], '@') != FALSE) {
            $temp_arr = explode('@', $result['Identity']);
            $domain = $temp_arr[1];
          }
          else {
            $domain = $result['Identity'];
          }
          foreach ($dkim_tokens as $token) {
            $name = (string) $token . '._domainkey.' . $domain;
            $value = (string) $token . '.dkim.amazonses.com';
            $result['member'][$key]['name'] = check_plain($name);
            $result['member'][$key]['value'] = check_plain($value);
            $result['member'][$key]['type'] = 'CNAME';
          }
        }
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action GetIdentityVerificationAttributes.
   *
   * This action is throttled at one request per second.
   */
  private function getIdentityVerificationAttributes($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->getIdentityVerificationAttributes([
        'Identities' => $action_parameter['Identities'],
      ]);
      if (!empty($response['VerificationAttributes'])) {
        foreach ($response['VerificationAttributes'] as $key => $value) {
          $result['data'][$key]['VerificationStatus'] = check_plain($value['VerificationStatus']);
          $result['data'][$key]['Identity'] = check_plain($key);

          // Token will be present if Identity id domain.
          if (isset($value['VerificationToken'])) {
            $domain_record_set = "<div class = ''><strong>Name: </strong> _amazonses.{$key} <br/>\n            <strong>Type:</strong> TXT <br/><strong>Value:</strong> {$value['VerificationToken']}";
            $result['data'][$key]['DomainRecordSet'] = $domain_record_set;
          }
        }
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action GetSendStatistics.
   *
   * The result is a list of data points, representing the last two weeks of
   * sending activity. Each data point in the list contains statistics for a 15
   * minute interval. This action is throttled at one request per second.
   */
  private function getSendStatistics($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->getSendStatistics([]);
      if (!empty($response['SendDataPoints'])) {

        // Number of emails that have been enqueued for sending.
        $result['DeliveryAttempts'] = 0;

        // Number of emails rejected by Amazon SES.
        $result['Rejects'] = 0;

        // Number of emails that have bounced.
        $result['Bounces'] = 0;

        // Number of unwanted emails that were rejected by recipients.
        $result['Complaints'] = 0;
        foreach ($response['SendDataPoints'] as $value) {
          $result['DeliveryAttempts'] = check_plain($value['DeliveryAttempts']) + $result['DeliveryAttempts'];
          $result['Rejects'] = check_plain($value['Rejects']) + $result['Rejects'];
          $result['Bounces'] = check_plain($value['Bounces']) + $result['Bounces'];
          $result['Complaints'] = check_plain($value['Complaints']) + $result['Complaints'];
        }
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }

    /* // Parse the xml response.
        $response = $response_xml->body->to_stdClass();
        if ($response_xml->status == '200') {
          $result['status'] = AMAZON_SES_REQUEST_SUCCESS;

          // Number of emails that have been enqueued for sending.
          $result['DeliveryAttempts'] = 0;
          // Number of emails rejected by Amazon SES.
          $result['Rejects'] = 0;
          // Number of emails that have bounced.
          $result['Bounces'] = 0;
          // Number of unwanted emails that were rejected by recipients.
          $result['Complaints'] = 0;
          if (isset($response->GetSendStatisticsResult->SendDataPoints->member)) {
            $member = $response->GetSendStatisticsResult->SendDataPoints->member;
            if (is_array($member)) {
              foreach ($member as $value) {
                $result['DeliveryAttempts'] = check_plain($value->DeliveryAttempts) + $result['DeliveryAttempts'];
                $result['Rejects'] = check_plain($value->Rejects) + $result['Rejects'];
                $result['Bounces'] = check_plain($value->Bounces) + $result['Bounces'];
                $result['Complaints'] = check_plain($value->Complaints) + $result['Complaints'];
              }
            }
            else {
              $result['DeliveryAttempts'] = check_plain($member->DeliveryAttempts);
              $result['Rejects'] = check_plain($member->Rejects);
              $result['Bounces'] = check_plain($member->Bounces);
              $result['Complaints'] = check_plain($member->Complaints);
            }

          }
        }
        // Error in response.
        else {
          $result['status'] = AMAZON_SES_REQUEST_FALIURE;
        }*/
    return $result;
  }

  /**
   * Call Query API action GetSendQuota.
   *
   * This action is throttled at one request per second.
   */
  private function getSendQuota($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->getSendQuota([]);
      if (!empty($response['Max24HourSend'])) {
        $result['SentLast24Hours'] = check_plain($response['SentLast24Hours']);
        $result['Max24HourSend'] = check_plain($response['Max24HourSend']);
        $result['MaxSendRate'] = check_plain($response['MaxSendRate']);
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action ListIdentities.
   *
   * This action is throttled at one request per second.
   */
  private function listIdentities($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->listIdentities([
        'IdentityType' => $action_parameter['IdentityType'],
        'MaxItems' => $action_parameter['MaxItems'],
      ]);
      if (!empty($response['Identities'])) {
        $result['member'] = $response['Identities'];
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action SendEmail.
   *
   * Composes an email message based on input data, and then immediately queues
   * the message for sending.
   */
  private function sendEmail($action_parameter) {
    $result['error'] = FALSE;
    try {
      $message = $action_parameter['mail'];
      dpm($message);
      $response = $this->sesClient
        ->sendEmail([
        'Destination' => [
          'ToAddresses' => [
            $message['to'],
          ],
        ],
        'Message' => [
          'Body' => [
            'Html' => [
              'Data' => $message['body'],
            ],
          ],
          'Subject' => [
            'Data' => $message['subject'],
          ],
        ],
        'ReplyToAddresses' => [
          $message['ReplyToAddresses'],
        ],
        'ReturnPath' => $message['ReturnPath'],
        'Source' => $message['from'],
      ]);
      if (!empty($response['MessageId'])) {
        $result['message_id'] = $response['MessageId'];
      }
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action VerifyEmailIdentity.
   *
   * Verifies an email address. This action causes a confirmation email message
   * to be sent to the specified address. This action is throttled at one
   * request per second.
   */
  private function verifyEmailIdentity($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->verifyEmailIdentity([
        'EmailAddress' => $action_parameter['EmailAddress'],
      ]);
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

  /**
   * Call Query API action VerifyDomaindentity.
   *
   * Verifies a domain.This action is throttled at one request per second.
   */
  private function verifyDomainIdentity($action_parameter) {
    $result['error'] = FALSE;
    try {
      $response = $this->sesClient
        ->verifyDomainIdentity([
        'Domain' => $action_parameter['Domain'],
      ]);
      $result['token'] = $response['VerificationToken'];
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    } catch (\Aws\Ses\Exception\SesException $e) {
      $result['message'] = $e
        ->getAwsErrorType();
      $result['errorCode'] = $e
        ->getAwsErrorCode();
      $result['error'] = TRUE;
    }
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AmazonSes::$sesClient private property
AmazonSes::deleteIdentity private function Call Query API action DeleteIdentity.
AmazonSes::getIdentityDkimAttributes private function Call Query API action GetIdentityNotificationAttributes.
AmazonSes::getIdentityVerificationAttributes private function Call Query API action GetIdentityVerificationAttributes.
AmazonSes::getSendQuota private function Call Query API action GetSendQuota.
AmazonSes::getSendStatistics private function Call Query API action GetSendStatistics.
AmazonSes::listIdentities private function Call Query API action ListIdentities.
AmazonSes::performServiceAction public function Add required parameter & header to the Query according to Query action.
AmazonSes::sendEmail private function Call Query API action SendEmail.
AmazonSes::verifyDomainIdentity private function Call Query API action VerifyDomaindentity.
AmazonSes::verifyEmailIdentity private function Call Query API action VerifyEmailIdentity.
AmazonSes::__construct public function Initiliaze this class.