Send email using Drupal 10

I have a php script inside the ‘/public/web’ directory. I send POST request from my js code to this script do some work and send email. Previously, I was sending email from this script using PHPMailer with my own custom email host and SMTP credentials and it worked. Now, I have to use Drupal’s email library so that it sends email as the system.

I tried several approach but could not succeed. My last attempt was to create a custom email module with ‘hook_email’ function and then calling that function from my php script. It seems, I have to Bootstrap Drupal into my custom php script before I could use any custom module or any of the Drupal’s library functions. But the bootstrapping process was not working.

I don’t have much experience with Drupal and could not find much Documentation regarding this. Thanks in advance!


I am posting my php script where I am trying to bootstrap Drupal.

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Component\Utility\SafeMarkup;

// Set the path to your Drupal root directory.
$drupal_root = '/vs/vhost/examplesite.com/public/web';
// Include the Drupal autoloader.
require_once $drupal_root . '/autoload.php';

// Create the request object from global variables.
$request = Request::createFromGlobals();

echo('Test 1');
// Bootstrap Drupal. This is where I am getting error.
$kernel = DrupalKernel::createFromRequest($request, $drupal_root, 'prod');


$kernel->boot();

// Set up the container and other necessary services.
$container = $kernel->getContainer();
$kernel->prepareLegacyRequest($request);

// Get the MailManager service.
$mailManager = $container->get('plugin.manager.mail');

// Prepare the email parameters.
$module = 'custom_module';  // Name of my custom module.
$key = 'custom_mail';        // A unique key to identify the email.
$to = 'my@email.com';
$params['message'] = 'This is a test email sent from a PHP script in Drupal 10.';
$params['subject'] = 'Test Email';
$langcode = $container->get('language_manager')->getDefaultLanguage()->getId();
$send = true;

// Send the email.
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

// Check the result of the email sending.
if ($result['result'] !== true) {
    echo "There was a problem sending your email.";
} else {
    echo "Your email has been sent successfully.";
}

I am getting following error after the echo statment: Error: Call to a member function addPsr4() on string in /vs/vhost/examplesite.com/public/web/core/lib/Drupal/Core/Database/Database.php on line 329 #0 /vs/vhost/examplesite.com/public/web/core/lib/Drupal/Core/Database/Database.php(384): Drupal\Core\Database\Database::addConnectionInfo(‘default’, ‘default’, Array, ‘/vs/vhost/canga…’, ‘/vs/vhost/canga…’)

I just need some advice on how to send email using Drupal’s email library from a php file that is in '/public/web’directory.

Sending emails using Drupal’s library from a standalone PHP script outside of Drupal’s normal execution flow is not recommended due to potential security risks and bootstrapping complexities. However, there are alternative approaches to achieve your goal:

1. Expose a Custom REST Endpoint:

  • Create a Custom Module: Develop a custom Drupal module that defines a REST endpoint for initiating email sending.
  • Implement Email Sending Logic: Within the module’s controller for the REST endpoint, use Drupal’s MailManagerInterface service to compose and send emails based on the received data from your JS code.
  • JavaScript Code Integration: Modify your JavaScript code to make a POST request to the newly created REST endpoint, passing the necessary email details (recipient, subject, message, etc.) in the request body.

2. Use a Dedicated Email Service:

  • Evaluate Alternatives: Consider using a dedicated email service like SendGrid, Mailgun, or Amazon SES. These services offer APIs that your JS code can interact with directly to send emails without the need for bootstrapping Drupal.
  • JS Code Integration: Integrate your JavaScript code with the chosen email service’s API to send emails directly, bypassing the need for Drupal’s email library.

3. Implement a Command Line Script (Cautionary Approach):

  • Security Concerns: This approach has security implications. Carefully manage access and permissioning for the script and only use it for trusted processes.
  • Custom Command Script: Create a custom Drupal command script that sends emails using the MailManagerInterface service.
  • Trigger Script Execution: Trigger the script execution from your JS code by making an Ajax request to a custom route that invokes the Drupal command. (Note: This requires additional development effort to handle cross-domain security considerations.)

Recommendation:

Out of the options above, exposing a custom REST endpoint within Drupal is the most secure and Drupal-friendly approach. It allows you to leverage Drupal’s email system while maintaining separation between your external script and Drupal’s core functionality.