如何从外部 php 文件(子文件夹)使用 drupal 邮件功能?

how to use drupal mail functionality from external php file (sub folder)?

我在我的 drupal 站点的子文件夹中使用核心 php 开发了一个单独的功能(假设类似于 mysite.com/myfolder/myfunc.php)。

现在我想像 drupal 站点一样发送电子邮件。

因为这不是自定义模块,所以我不能使用 hook_mail。或者有没有可能实现这个?

如何从核心 php(站点的子文件夹)使用 drupal 邮件功能?

最好的方法是创建一个模块,但如果需要,您可以使用

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/**
Write your code here
use PHP core, drupal core and contrib functions
**/

同意@AZinkey。一种方法是包括 drupal 的 bootstrap 并提供所有 drupal 的功能,如他所解释的那样。但更好的方法是从 Drupal 定义您的页面。查看 drupal 的 hook_menu 函数:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

就像那里解释的那样:

function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}
function mymodule_abc_view($ghi = 0, $jkl = '') {

  // ...
}

..您可以轻松定义自定义页面。您只需要页面路径("abc/def")和传递页面内容的函数("mymodule_abc_view")。

为了参考,我将代码放在这里。它可能是完整的代码,但这可能会对某人有所帮助。

//These lines are to use drupal functions
define('DRUPAL_ROOT', 'Your/drupal/path');
require_once '../../../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

//Get the mail content
$email_content = get_mail_content();
$params = array('body' => $email_content);
$key = 'test_email'; //this is the key
$to = 'siddiqxxxxx@gmail.com';
$from = 'support@xxxxx.com';

//use the hook_mail name here. in my case it is 'test'.
$mail = drupal_mail('test', $key, $to, language_default(), $params, $from);
echo "Mail sent";

//using hook_mail. we can use whatever the name we want. Parameters are just fine.
function test_mail($key, &$message, $params) {
  $language = $message['language'];
  switch ($key) {
//switching on $key lets you create variations of the email based on the $key parameter
    case 'test_email': //this is the key
      $message['subject'] = t('Test Email');
//the email body is here, inside the $message array
      $message['body'][] = $params['body'];
      break;
  }
}


function get_mail_content() {

  $email_to = 'siddiqxxxxx@gmail.com';
  $pos = strpos($email_to, '@');
  $user_name = substr($email_to, 0, $pos);
  $body = '';
  $body .= 'Hi ' . $user_name . '<br>';
  $body .= 'Please find my test email. <br>';
  $body .= 'This is the email body' . '<br>';
  $body .= 'Thanks<br>';
  $body .= 'TestTeam';
  return $body;
}