Answers:
使用hook_mail和drupal_mail可以创建和发送电子邮件。
使用hook_mail实现电子邮件:
function MODULENAME_mail ($key, &$message, $params) {
switch ($key) {
case 'mymail':
// Set headers etc
$message['to'] = 'foo@bar.com';
$message['subject'] = t('Hello');
$message['body'][] = t('Hello @username,', array('@username' => $params['username']));
$message['body'][] = t('The main part of the message.');
break;
}
}
要发送邮件,请使用drupal_mail:
drupal_mail($module, $key, $to, $language, $params = array('username' => 'John Potato'), $from = NULL, $send = TRUE)
显然替换参数:$ key应该等于'mymail'
只需几个步骤即可发送电子邮件:
$message['to']
中,硬编码为foo@bar.com
。忽略此选项,邮件将被发送到drupal_mail()
被调用时指定的收件人。
如果您想以更简单的方式发送电子邮件,请查看“ 简单邮件”;这是我正在致力于使使用Drupal 7+发送电子邮件变得更加容易的模块,并且它不需要任何额外的挂钩实现或MailSystem知识。发送电子邮件非常简单:
simple_mail_send($from, $to, $subject, $message);
您可以使用一种更简单的发送电子邮件的方法,查看mailsystem;这是一个模块。
<?php
$my_module = 'foo';
$from = variable_get('system_mail', 'organization@example.com');
$message = array(
'id' => $my_module,
'from' => $from,
'to' => 'test@example.com',
'subject' => 'test',
'body' => 'test',
'headers' => array(
'From' => $from,
'Sender' => $from,
'Return-Path' => $from,
),
);
$system = drupal_mail_system($my_module, $my_mail_token);
if ($system->mail($message)) {
// Success.
}
else {
// Failure.
}
?>
您可以在自定义模块中选择使用以下代码:
function yourmodulename_mail($from = 'default_from', $to, $subject, $message) {
$my_module = 'yourmodulename';
$my_mail_token = microtime();
if ($from == 'default_from') {
// Change this to your own default 'from' email address.
$from = variable_get('system_mail', 'admin@yoursite.com');
}
$message = array(
'id' => $my_module . '_' . $my_mail_token,
'to' => $to,
'subject' => $subject,
'body' => array($message),
'headers' => array(
'From' => $from,
'Sender' => $from,
'Return-Path' => $from,
),
);
$system = drupal_mail_system($my_module, $my_mail_token);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
} else {
return FALSE;
}
}
然后您可以使用上述功能,例如:
$user = user_load($userid); // load a user using its uid
$usermail = (string) $user->mail; // load user email to send a mail to it OR you can specify an email here to which the email will be sent
customdraw_mail('default_from', $usermail, 'You Have Won a Draw -- this is the subject', 'Congrats! You have won a draw --this is the body');