官术网_书友最值得收藏!

Implementing hook_mail()

As I mentioned earlier, the first step for sending mails in Drupal 8 is implementing hook_mail(). In our case, it can look something like this:

/**
* Implements hook_mail().
*/
function hello_world_mail($key, &$message, $params) {
switch ($key) {
case 'hello_world_log':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('There is an error on your website');
$message['body'][] = $params['message'];

break;
}
}

This hook receives three parameters--the message key (template) that is used to send the mail, the message of the email that needs to be filled in, and an array of parameters passed from the client code. As you can see, we are defining a key (or template) named hello_world_log, which has a simple static subject, and as a body, it will have whatever comes from the $parameters array in its message key. Since the email From is always the same, we will use the site-wide email address that can be found in the system.site configuration object. You'll note that we are not in a context where we can inject the configuration factory as we did when we built the form. Instead, we can use the static helper to load it.

Additionally, you'll note that the body is itself an array. This is because we can build (if we want) multiple items in that array that can be later imploded as paragraphs in the mail plugin's format() method. This is in any case what the default mail plugin does, so here we need to build an array.

Another useful key in the $message array is the header key, which you can use to add some custom headers to the mail. In this case, we don't need to because the default PhpMail plugin adds all the necessary headers. Also, if we write our own mail plugin, we can then add our headers in there as well--and all other keys of the $message array, for that matter. This is because the latter is passed around as a reference, so it keeps getting built up in the process from the client call to the hook_mail() implementation to the plugin.

That is about all we need to do with hook_mail(). Let's now see how to use this in order to send out an email.

主站蜘蛛池模板: 白沙| 扎鲁特旗| 阿巴嘎旗| 宜春市| 鲁甸县| 科尔| 宁城县| 司法| 宁河县| 宁强县| 广灵县| 克什克腾旗| 新和县| 陇川县| 土默特右旗| 锡林郭勒盟| 同德县| 平原县| 浦城县| 黄大仙区| 浦城县| 新宁县| 泾阳县| 东阿县| 茶陵县| 鲁甸县| 枣庄市| 丰城市| 新邵县| 多伦县| 常德市| 昭觉县| 博兴县| 远安县| 张北县| 深圳市| 高青县| 临沭县| 滦平县| 凤庆县| 和政县|