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.