Send mail via SparkPost REST API

@param \Cake\Mailer\Email $email Email message
@return array
761973
public function send(Email $email)
    {
        // Load SparkPost configuration settings
        $apiKey = $this->config('apiKey');

        // Set up HTTP request adapter
        $adapter = new CakeHttpAdapter(new Client());

        // Create SparkPost API accessor
        $sparkpost = new SparkPost($adapter, [ 'key' => $apiKey ]);

        // Pre-process CakePHP email object fields
        $from = (array) $email->from();
        $sender = sprintf('%s <%s>', mb_encode_mimeheader(array_values($from)[0]), array_keys($from)[0]);
        $to = (array) $email->to();
        $replyTo = $email->getReplyTo() ? array_values($email->getReplyTo())[0] : null;
        
        foreach ($to as $toEmail => $toName) {
            $recipients[] = ['address' => [ 'name' => mb_encode_mimeheader($toName), 'email' => $toEmail]];
        }

        // Build message to send
        $message = [
            'from' => $sender,
            'html' => empty($email->message('html')) ? $email->message('text') : $email->message('html'),
            'text' => $email->message('text'),
            'subject' => mb_decode_mimeheader($email->subject()),
            'recipients' => $recipients
        ];
        
        if ($replyTo) {
	    $message['replyTo'] = $replyTo;
	}

        // Send message
        try {
            $sparkpost->transmission->send($message);
        } catch(APIResponseException $e) {
            // TODO: Determine if BRE is the best exception type
            throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)',
                $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription()));
        }
    }
180801
protected function buildMessage(EmailEntity $email)
    {
        // Create attachments array
        $attachments = json_decode($email->getAttachments(), true);

        $recipientEmail = $email->getRecipientEmail();

        $to = [
            [
                'email' => $this->filterThroughWhitelist($recipientEmail),
                'name'  => $email->getRecipientName(),
                'type'  => 'to'
            ]
        ];

        $message = [
            'html'                => $email->getMessage(),
            'subject'             => $email->getSubject(),
            'from_email'          => $email->getSenderEmail(),
            'from_name'           => $email->getSenderName(),
            'to'                  => $to,
            'attachments'         => $attachments,
            'headers'             => json_decode($email->getHeaders(), true),
            'important'           => false,
            'track_opens'         => true,
            'track_clicks'        => true,
            'auto_text'           => true,
            'auto_html'           => false,
            'inline_css'          => true,
            'url_strip_qs'        => null,
            'preserve_recipients' => false,
            'bcc_address'         => $email->getBcc(),
            'merge'               => true,
        ];

        return $message;
    }
1210972
public function setEmail($email)
    {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->_options['email'] = $email;
            $this->_options['hash'] = strtolower(md5(trim($this->_options['email'])));
        } else {
            throw new \Exception('The email is in an invalid format!');
        }

        return $this;
    }
464224
public static function getByEmail($email)
    {
        $fields = self::getDbConnection()->fetchAssoc('SELECT * FROM '.User::TABLE.' WHERE email = ?', array($email));
        if (!$fields) return false;
        return self::fetch($fields);       
  	}
461575
public function findUserByEmail($email)
    {
        $qb = $this->createQueryBuilder('user')
            ->where('user.email=:email');

        $query = $qb->getQuery();
        $query->setParameter('email', $email);

        return $query->getSingleResult();
    }
771528
public function setEmail($email)
    {
        $email = (string) $email;

        if ($this->exists() && $this->email !== $email) {
            $this->updated['email'] = true;
        }

        $this->email = $email;

        return $this;
    }
1219197
public function send(Email $email)
    {
        $message = [
            'html' => $email->message(Email::MESSAGE_HTML),
            'text' => $email->message(Email::MESSAGE_TEXT),
            'subject' => mb_decode_mimeheader($email->getSubject()), // Decode because SendGrid is encoding
            'from' => key($email->getFrom()),
            'fromname' => current($email->getFrom()),
            'to' => [],
            'toname' => [],
            'cc' => [],
            'ccname' => [],
            'bcc' => [],
            'bccname' => [],
            'replyto' => $email->getReplyTo() ? array_values($email->getReplyTo())[0] : key($email->getFrom()),
        ];
        // Add recipients
        $recipients = [
            'to' => $email->getTo(),
            'cc' => $email->getCc(),
            'bcc' => $email->getBcc()
        ];
        foreach ($recipients as $type => $emails) {
            foreach ($emails as $mail => $name) {
                $message[$type][] = $mail;
                $message[$type . 'name'][] = $name;
            }
        }

        // Create a new scoped Http Client
        $this->http = new Client([
            'host' => 'api.sendgrid.com',
            'scheme' => 'https',
            'headers' => [
                'User-Agent' => 'CakePHP SendGrid Plugin'
            ]
        ]);

        $message = $this->_attachments($email, $message);

        return $this->_send($message);
    }
792549
protected function sendMagicLinkNotification(string $email, string $token) : array
  {
    return Notification::make(new MustLogin($email, $token));
  }
957249
public function getSubscriberDataByEmails($emails)
    {
        $subscriberFactory = $this->subscriberFactory->create();
        $subscribersData = $subscriberFactory->getCollection()
            ->addFieldToFilter(
                'subscriber_email',
                ['in' => $emails]
            )
            ->addFieldToSelect(['subscriber_email', 'store_id']);

        return $subscribersData->toArray();
    }
683783
public function send(Email $email)
    {
        if (!$this->connected()) {
            $this->_connect();
            $this->_auth();
        } else {
            $this->_smtpSend('RSET');
        }

        $this->_sendRcpt($email);
        $this->_sendData($email);

        if (!$this->_config['keepAlive']) {
            $this->_disconnect();
        }

        return $this->_content;
    }
527271
public function show($email)
    {
        $url = $this->client->url . '/rest/v1/leads.json';
        $queryParams = [
            'filterType' => 'email',
            'filterValues' => $email
        ];
        $response = parent::get($url, $queryParams);
        if ($response->success) {
            if (count($response->result) > 0) {
                return $response->result[0];
            } else {
                throw new LeadDoesNotExistException('Lead does not exist with email ' . $email);
            }
        } else {
            throw new MarketoApiException('Error retrieving lead: ' . $response->errors[0]->message);
        }
    }
1363344
protected function _send($message)
    {
        $options = [
            'headers' => ['Authorization' => 'Bearer ' . $this->getConfig('api_key')]
        ];
        $response = $this->http->post('/api/mail.send.json', $message, $options);
        if ($response->getStatusCode() !== 200) {
            throw new SendgridEmailException(sprintf(
                'SendGrid error %s %s: %s',
                $response->getStatusCode(),
                $response->getReasonPhrase(),
                implode('; ', $response->json['errors'])
            ));
        }

        return $response->json;
    }
113248
public function do_SendMail($email, $type, $key)
    {
        $return = [
            'error' => true
        ];
        $mail = new PHPMailer();

        // Check configuration for custom SMTP parameters
        try {
            // Server settings
            if ($this->config->smtp) {

                if ($this->config->smtp_debug) {
                    $mail->SMTPDebug = $this->config->smtp_debug;
                }

                $mail->isSMTP();

                $mail->Host = $this->config->smtp_host;
                $mail->SMTPAuth = $this->config->smtp_auth;

                // set SMTP auth username/password
                if (!is_null($this->config->smtp_auth)) {
                    $mail->Username = $this->config->smtp_username;
                    $mail->Password = $this->config->smtp_password;
                }

                // set SMTPSecure (tls|ssl)
                if (!is_null($this->config->smtp_security)) {
                    $mail->SMTPSecure = $this->config->smtp_security;
                }

                $mail->Port = $this->config->smtp_port;
            } //without this params internal mailer will be used.

            //Recipients
            $mail->setFrom($this->config->site_email, $this->config->site_name);
            $mail->addAddress($email);

            $mail->CharSet = $this->config->mail_charset;

            //Content
            $mail->isHTML(true);

            if ($type == 'activation') {
                $mail->Subject  = $this->__lang('email_activation_subject', $this->config->site_name);
                $mail->Body     = $this->__lang('email_activation_body', $this->config->site_url, $this->config->site_activation_page, $key);
                $mail->AltBody  = $this->__lang('email_activation_altbody', $this->config->site_url, $this->config->site_activation_page, $key);
            } elseif ($type == 'reset') {
                $mail->Subject  = $this->__lang('email_reset_subject', $this->config->site_name);
                $mail->Body     = $this->__lang('email_reset_body', $this->config->site_url, $this->config->site_password_reset_page, $key);
                $mail->AltBody  = $this->__lang('email_reset_altbody', $this->config->site_url, $this->config->site_password_reset_page, $key);
            } else {
                return false;
            }

            if (!$mail->send())
                throw new \Exception($mail->ErrorInfo);

            $return['error'] = false;

        } catch (\Exception $e) {
            $return['message'] = $mail->ErrorInfo;
        }

        return $return;
    }
583799
public function setBcc($email)
    {
        if (is_string($email)) {
            // Means we have a straight email
            $email = [ $email ];
        }

        if (!is_array($email)) {
            throw new InvalidArgumentException(
                'Must be an array of BCC recipients.'
            );
        }

        $this->bcc = [];

        // At this point, `$email` can be an _email array_ or an _array of emails_...
        if (isset($email['email'])) {
            // Means we're not dealing with multiple emails
            $this->addBcc($email);
        } else {
            foreach ($email as $recipient) {
                $this->addBcc($recipient);
            }
        }

        return $this;
    }
1281818
public static function getByEmail(string $email) : Users
    {
        $user = self::findFirst([
            'conditions' => 'email = ?0',
            'bind' => [$email]
        ]);

        if (!$user) {
            throw new Exception('No User Found');
        }

        return $user;
    }
228628
public function email($email)
    {
        if (! is_string($email) && ! is_array($email)) {
            throw new InvalidArgumentException('The email can be only string or array');
        }

        $this->emailTo = is_array($email) ? $email : [$email];

        // Force the job to run in foreground
        $this->inForeground();

        return $this;
    }
1256381
protected function _sendData($email)
    {
        $this->_smtpSend('DATA', '354');

        $headers = $this->_headersToString($this->_prepareMessageHeaders($email));
        $message = $this->_prepareMessage($email);

        $this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
        $this->_content = ['headers' => $headers, 'message' => $message];
    }