Build Mandrill compatible message array from email entity

Documentation at https://mandrillapp.com/api/docs/messages.php.html

@param  EmailEntity  $emails
@return array
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;
    }
906917
public static function buildMultiply($entities)
    {
        $templates = [];

        foreach ($entities as $entity) {
            $templates[$entity->language] = static::buildFromEntity($entity);
        }

        return $templates;
    }
533538
protected function updateEmail(Email $email, $entry)
    {
        $success = true;

        $emailType = $this->em
            ->getRepository(self::$emailTypeEntityName)
            ->find($entry['emailType']['id']);

        if (!$emailType) {
            throw new EntityNotFoundException(self::$emailTypeEntityName, $entry['emailType']['id']);
        } else {
            $email->setEmail($entry['email']);
            $email->setEmailType($emailType);
        }

        return $success;
    }
291087
protected function buildEnvelope($method = 'email', $email = null, $message = null)
    {
        return new Envelope(
                array(
                    'sendMethod' => $method,
                    'email' => $email,
                    'invoiceEmail' => $message,
                )
        );
    }
499658
public function convert(Email $email): \Swift_Message
    {
        $message = $this->createInstance()->setSubject($email->getSubject());
        $message->setBoundary($boundary = \md5(\uniqid()));

        $this->addAddresses($email, $message);
        $this->addParts($email, $message, $boundary);
        $this->addHeaders($email, $message);
        $this->addAttachments($email, $message);

        if ($contentType = $email->getContentType()) {
            $message->setContentType($contentType);
        }

        return $message;
    }
116898
public function deleteConsentByEmails($emails)
    {
        if (empty($emails)) {
            return [];
        }
        $collection = $this->consentCollectionFactory->create();
        $collection->getSelect()
            ->joinInner(
                ['c' => $this->getTable(Schema::EMAIL_CONTACT_TABLE)],
                "c.email_contact_id = main_table.email_contact_id",
                []
            );

        $collection->addFieldToFilter('c.email', ['in' => $emails]);

        return $collection->walk('delete');
    }
1303929
protected function getImportErrors(EntityInterface $entity): array
    {
        $result = [];

        /**
         * @var array $errors
         */
        $errors = $entity->errors();

        if (empty($errors)) {
            return $result;
        }

        foreach ($errors as $field => $error) {
            $msg = "[$field] ";
            $msg .= is_array($error) ? implode(', ', $error) : $error;
            $result[] = $msg;
        }

        return $result;
    }
228465
public function getEmails()
    {
        $entities = [];
        if ($this->entity->getEmails()) {
            foreach ($this->entity->getEmails() as $email) {
                $entities[] = $email;
            }
        }

        return $entities;
    }
481384
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient)
    {
        $notificationData = $notification->getNotificationData();
        $locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']);
        if ($locale === null) {
            throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID']));
        }
        $uir = $this->app->make(UserInfoRepository::class);
        $packageVersion = $notificationData['packageVersionID'] ? $this->app->make(PackageVersionRepository::class)->find($notificationData['packageVersionID']) : null;
        $translations = [];
        foreach ($notificationData['numTranslations'] as $userID => $numTranslations) {
            $translations[] = [
                'user' => $uir->getByID($userID),
                'numTranslations' => $numTranslations,
            ];
        }

        return [
            'localeName' => $locale->getDisplayName(),
            'translations' => $translations,
            'approvalURL' => (string) URL::to(
                $this->app->make('community_translation/config')->get('options.onlineTranslationPath'),
                $packageVersion ? $packageVersion->getID() : 'unreviewed',
                $locale->getID()
            ),
        ] + $this->getCommonMailParameters($notification, $recipient);
    }
194278
public static function getUploadHeaders(ImportEntity $entity) : array
    {
        $reader = Reader::createFromPath($entity->filename, 'r');

        return $reader->fetchOne();
    }
580524
public function fromEmail(Email $emailEntity)
    {
        $message = (new \Swift_Message())
            ->setSubject($emailEntity->getSubject())
            ->setTo([$emailEntity->getTargetMail()])
            ->setFrom($emailEntity->getFrom())
            ->setBody($emailEntity->getBodyHtml(), 'text/html')
            ->addPart($emailEntity->getBodyText(), 'text/plain');

        foreach ($emailEntity->getAttachments() as $name => $attachment) {
            $message->attach(AttachmentManager::buildSwift($attachment, $name));
        }

        return $message;
    }
515072
protected function getRecipients(Swift_Mime_Message $message) {
        $to = [];
        if ($message->getTo()) {
            $to = array_merge($to, $message->getTo());
        }
        if ($message->getCc()) {
            $to = array_merge($to, $message->getCc());
        }
        if ($message->getBcc()) {
            $to = array_merge($to, $message->getBcc());
        }
        $recipients = [];
        foreach ($to as $address => $name) {
            if (!is_null($name)) {
                $recipients[] = ['Email' => $address, 'Name' => $name];
            } else {
                $recipients[] = ['Email' => $address];
            }
        }
        return $recipients;
    }
1038747
protected function generateMessage($email, $message)
    {
        foreach ($message->getToWithCarriers() as $number) {
            $email->to($this->buildEmail($number, $message));
        }

        if ($message->getAttachImages()) {
            foreach ($message->getAttachImages() as $image) {
                $email->attach($image);
            }
        }

        $email->from($message->getFrom());

        return $email;
    }
981770
public function buildMessages(
        string $fieldName,
        ValidationResult $validationResult,
        array $messages = [],
        array $options = []
    ): array {
        if ($validationResult instanceof ValidationResultFields) {
            $options[Field::KEY_FIELD_NAME] = $fieldName;
            $subMessages = $this->buildMessagesValidationFields(
                $validationResult->getFieldResults(),
                [],
                $options
            );

            $messages = $this->flattenSubMessages(
                $fieldName,
                $subMessages,
                $messages
            );

            return $messages;
        }

        $options[Field::KEY_FIELD_NAME] = $fieldName;
        $messages[$fieldName] = $this->getMessagesValidationResult->__invoke(
            $validationResult,
            $options
        );

        return $messages;
    }
1234415
public function getRecipientsFromPost(array $referenced_entity) {
    $recipients = [];

    $post = Post::load($referenced_entity['target_id']);
    $recipient_user = $post->get('field_recipient_user')->getValue();
    if (!empty($recipient_user)) {
      $recipients[] = [
        'target_type' => 'user',
        'target_id' => $recipient_user['0']['target_id'],
      ];
    }

    return $recipients;
  }
1247947
public function getRecipientsWhoFollowContent(array $related_entity, array $data) {
    $recipients = [];

    $storage = \Drupal::entityTypeManager()->getStorage('flagging');
    $flaggings = $storage->loadByProperties([
      'flag_id' => 'follow_content',
      'entity_type' => $related_entity['target_type'],
      'entity_id' => $related_entity['target_id'],
    ]);

    // We don't send notifications to users about their own comments.
    $original_related_object = $data['related_object'][0];
    $storage = \Drupal::entityTypeManager()
      ->getStorage($original_related_object['target_type']);
    $original_related_entity = $storage->load($original_related_object['target_id']);

    foreach ($flaggings as $flagging) {
      $recipient = $flagging->getOwner();
      if ($recipient->id() != $original_related_entity->getOwnerId()) {
        if ($original_related_entity->access('view', $recipient)) {
          $recipients[] = [
            'target_type' => 'user',
            'target_id' => $recipient->id(),
          ];
        }
      }
    }

    return $recipients;
  }
442884
public function getEmailsGlobalInfo($emails) {
        if (empty($emails)) {
            return $this->handleError('Empty emails list');
        }

        $requestResult = $this->sendRequest('emails', 'POST', $emails);

        return $this->handleResult($requestResult);
    }