无法通过Drupal 8发送电子邮件

时间:2018-08-01 22:12:35

标签: php drupal-8

我正在Drupal 8中开发一个自定义模块。我正在尝试发送有关表单提交的电子邮件。我在服务器上安装了邮件客户端程序,并且能够从服务器中的命令行发送电子邮件,但是当我尝试从devel发送电子邮件以测试我的网站不起作用时,它什么也没有返回。我尝试使用\ Drupal \ Core \ Mail \ Plugin \ Mail \ PhpMail();和\ Drupal :: service('plugin.manager.mail');

    $mailManager = \Drupal::service('plugin.manager.mail');
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $params['context']['subject'] = 'Subject';
    $params['context']['message'] = 'body';
    $to = 'myorgemail@company.test';
    $result['result'] = $mailManager->mail('system', 'mail', $to, $langcode, $params);
    dpm($result['result']);   

我尝试的另一种方法是

    $send_mail = new \Drupal\Core\Mail\Plugin\Mail\PhpMail(); 
    $from = 'from_email_given';
    $message['headers'] = array(
    'content-type' => 'text/html',
    'MIME-Version' => '1.0',
    'reply-to' => $from,
    'from' => 'sender name <'.$from.'>');
    $message['to'] = 'to_email_given';
    $message['subject'] = 'Subject Goes here !!!!!';
    $message['body'] = 'Hello'; 
    $send_mail->mail($message); 

两种方式我都没有收到电子邮件。我不确定如何调试和解决这个问题。如果需要,请问我更多信息。

2 个答案:

答案 0 :(得分:1)

这是服务器设置问题。我们必须在服务器上打开“ httpd_can_sendmail”配置。

setsebool -P httpd_can_sendmail 1

答案 1 :(得分:-1)

使用以下代码在Drupal 8中发送邮件

$params = [];
$params['message'] = 'Mail Body';
$params['subject'] = 'Sample Subject';
$to = 'example@gmail.com';

//Calling drupal Mail service
$mailManager = \Drupal::service('plugin.manager.mail');
//Module Name
$module = 'custom_mail_sending';
//Static Mail Key
$key = 'custom_mail_sending_key';
//Email Language
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;

$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] != true) {     
  $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
  drupal_set_message($message, 'error');
  \Drupal::logger('custom_mail_sending_log')->notice($message);
} else {
  $message = t('An email notification has been sent to @email ', array('@email' => $to));
  drupal_set_message($message,'status');
  \Drupal::logger('custom_mail_sending_log')->error($message);
}