1

I am developing a custom module in Drupal 8. I am trying to send an email on form submission. I installed mail client on my server and able to send email from command line in the server but when I am trying to send email from devel to test my site its not working.Its returning nothing. I tried with \Drupal\Core\Mail\Plugin\Mail\PhpMail(); and \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']);   

The other way which I tried is

    $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); 

both the ways I am not receiving the email. I am not sure how to debug and solve this. Please ask me more information if needed.

user3324848
  • 181
  • 1
  • 4
  • 17

2 Answers2

0

It was a server setting issue. We had to turn on the "httpd_can_sendmail" configuration on server.

setsebool -P httpd_can_sendmail 1
user3324848
  • 181
  • 1
  • 4
  • 17
-1

Use below code to sending mails in 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);
}
Vernit Gupta
  • 339
  • 1
  • 10