Adelaide, AUS
Account created on 31 March 2001, about 24 years ago
#

Recent comments

🇦🇺Australia singularo Adelaide, AUS

Adding the composer.json means its now possible to include the branch version with changes like:

"repositories": [
{
"type": "composer",
"url": "https://packages.drupal.org/8",
"exclude": [
"drupal/field_prefix"
]
},
[other things here]
],
"require": {
[other things here]
"drupal/field_prefix": "dev-3357303-extend-and-add"
[other things here]
}

🇦🇺Australia singularo Adelaide, AUS
  • Create a Dynamic template in the SendGrid UI with fields to match those in the $this->mail->addSubstitutions() call
  • Create a simple module of your own or use an existing one
  • In the src/Plugin/Mail directory, create a new class like the example below, which extends the SendGridMail class
  • Enable the module
  • Select the new plugin in the mailsystem page
  • Send test email to confirm all working

Example class:

<?php

namespace Drupal\your_module\Plugin\Mail;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\sendgrid_mailer\Plugin\Mail\SendGridMail;
use SendGrid\Mail\Mail;

/**
 * Defines the default Drupal mail backend, using SendGrid API.
 *
 * @Mail(
 *   id = "custom_sendgrid_mail",
 *   label = @Translation("Custom SendGrid mailer"),
 *   description = @Translation("Sends emails using SendGrid API")
 * )
 */
class CustomSendGridMail extends SendGridMail implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function format(array $message) {
    if (is_array($message['body'])) {
      $message['body'] = implode("\n\n", $message['body']);
    }

    return $message;
  }

  /**
   * {@inheritdoc}
   */
  public function mail(array $message) {
    try {
      $this->mail = new Mail();

      $this->setFrom($message);

      $this->addHeaders($message);

      $this->addRecipients($message);

      $this->mail->setSubject($message['subject']);
      $this->mail->setTemplateId('<template id from sendgrid>');
      $this->mail->addSubstitutions([
        'name' => $message['params']['account']->getDisplayName(),
        'subject' => $message['subject'],
        'notification_message' => $message['body'],
      ]);

      $this->addAttachments($message);

      $response = $this->sendGrid->client->mail()->send()->post($this->mail);
      if ($response->statusCode() !== 202) {
        watchdog_exception('sendgrid_mailer', new \Exception('SendGrid Error'), $response->body());
      }

      return $response->statusCode() === 202;
    }
    catch (\Exception $e) {
      watchdog_exception('sendgrid_mailer', $e, $e->getMessage());
    }

    return FALSE;
  }

}
Production build 0.71.5 2024