Differences

This shows you the differences between two versions of the page.

Link to this comparison view

moodle:email [2017/12/30 09:29]
moodle:email [2016/01/14 15:39] (current)
onno [Plain Text Version]
Line 1: Line 1:
 +====== Email ======
  
 +Use the standard ''email_to_user'' function and hack its arguments to do more advanced stuff. ATTENTION: adding cc and bcc headers in this way only works if you're **not** using smtp.
 +
 +Here's how you add a Bcc header:
 +
 +<code>
 +        $from = generate_email_supportuser();
 +        $from->customheaders = "Bcc: mysecret.address@solin.eu";
 +        email_to_user($user, $from, $subject, $messagetext);
 +</code>
 +
 +Update: use ''core_user::get_support_user();''. As a matter of fact, it looks as though the customheaders should be an array now:
 +
 +<code>
 +        $from = core_user::get_support_user();
 +        $from->customheaders = array("Bcc: mysecret.address@solin.eu", "Cc: onno@solin.nl"); 
 +        email_to_user($user, $from, $subject, $messagetext);
 +</code>
 +
 +===== Plain Text Version =====
 +
 +Use ''html_to_text'' to create a proper plain text version out of your html email. Example:
 +<code>
 +email_to_user($user, $supportuser, $subject, html_to_text($messagehtml), $messagehtml);
 +</code>
 +
 +Please note that the $user's property ''mailformat'' determines the email layout. If ''$user->mailformat == 1'' then the html format is used, otherwise plain text. The site wide user preference default is can be retrieved through ''$CFG->defaultpreference_mailformat''. If you use ''$user = core_user::get_user($user_id)'', then the $user will contain the ''mailformat'' property.
 +==== Filling a new (dummy) user with the correct info ====
 +
 +Sometimes you have to send e-mail to users who don't exists yet. Instead of creating a dummy user object, there is a some simple functions who can do that for you, which are called ''user_picture::fields()'' and ''username_load_fields_from_object()''. 
 +
 +Usually creating a dummy user object goes something like this:
 +
 +<code>
 +    $postuser = new stdClass;
 +    $postuser->id        = $post->userid;
 +    $postuser->firstname = $post->firstname;
 +    $postuser->lastname  = $post->lastname;
 +    $postuser->imagealt  = $post->imagealt;
 +    $postuser->picture   = $post->picture;
 +    $postuser->email     = $post->email;
 +</code>
 +
 +But you can make it easier by using the other functions to create a simple user object from the information you probably already have.
 +
 +<code>
 +   $to_user = new stdClass();
 +   $userfields = explode(',', user_picture::fields());
 +   $to_user = username_load_fields_from_object($to_user, $invitation, null, $userfields);
 +   $to_user->id = -1;
 +</code>

Personal Tools