views:

54

answers:

3

hi,

I need to send an e-mail from my custom php code using the Drupal service.

In other words, I've noticed Drupal can easily send emails so I would like to know how can I use drupal libraries to send the emails, instead of using external libraries.

thanks

+3  A: 

You need to use the drupal_mail() function, and defined a hook_mail() in your module.

You'll then call the first one, and the e-mail informations will be set by the second one.
(See the example on the manual page of drupal_mail)

Pascal MARTIN
if I have my php code in a script how do I invoke the correct hook. In other words, if I invoke drupal_mail(), how can I refer to the right hook_mail() ?
Patrick
Read the documentation page Pascal referred to. Quote: `// example_mail() will be called based on the first drupal_mail() parameter.`
marcvangend
A: 
$message = array(
  'to' => '[email protected]',
  'subject' => t('Example subject'),
  'body' => t('Example body'),
  'headers' => array('From' => '[email protected]'),
);

drupal_mail_send($message);

Caveats:

  • Because drupal_mail() isn't called, other modules will not be able to hook_mail_alter() your output, which can cause unexpected results.
  • drupal_mail_send() is ignorant about which language to send the message in, so this needs to be figured out beforehand.
  • You'll have to manually specify any other e-mail headers that are required ('Content-Type', etc.). These are normally taken care of for you by drupal_mail(). In the case where your module sends several different types of e-mails, and you want those e-mail templates to be editable (for example, user module's various registration notification/password reset/etc. e-mails), using hook_mail() is still the best way to go.

This is what reported in the comments section in the documentation for drupal_mail(). If the caveats are not important in your case, then you can use the reported snippet.

kiamlaluno
+1  A: 

I would recommend to use mimemail. It's a contrib module that will allow you to send HTML mails (+ attachments) or plaintext-only messages with ease. Here is an excerpt from the readme file:

the mimemail() function:

  • $sender - a user object or email address
  • $recipient - a user object or email address
  • $subject - subject line
  • $body - body text in html format
  • $plaintext - boolean, whether to send messages in plaintext-only (default false)

This module creates a user preference for receiving plaintext-only messages. This preference will be honored by all calls to mimemail()

Link: http://drupal.org/project/mimemail

I hope this will help you!

mikewink
thanks for this tip. Although the solution to the question was simply drupal_mail, I'm now using mimemail because I need to send attachments. Please check this my new question if you have time: http://stackoverflow.com/questions/3258760/drupal-mimemail-e-mails-without-attachment
Patrick

related questions