The variables available to the system emails are very limited (!username, !site, !password, !uri, !uri_brief, !mailto, !date, !login_uri, !edit_uri, !login_url)

I've been asked to add a variable containing the user's first and last name to the welcome email.

Using the profile module, I customized the registration form to capture the first and last name.

How can I modify the variables available to the welcome email so as to include the user's first and last name? Where would I define and set the variables?

Any help is greatly appreciated.

Comments

CarbonPig’s picture

Anyone Know??

rajeshh’s picture

i am also having the same problem.Did u find the solution for it

hhanna’s picture

I ended up writing my own module to modify the registration email from drupal. This module makes the following replacements tokens available: !first, !middle, !last, !fullname, !username, !site. So, you must add these tokens to your email subject/body using the adminstration interface: administer > user management > user settings > user email settings.

Basically, when you send an email, you're usually using a form, so right there it opens the door to modifying the form contents:

1. I use hook_form_alter() to inject the new script in the form processing flow.
2. I use hook_mail_alter() to get the registrant name and make the replacements based on which form is being processed.
3. Using the site administration interface, I add the tokens to be replaced in the message fields.

Caveats:
1. You have to be using the profile module to have added the first, middle, last fields to the registration form. This script queries the profile tables to get the first, last, middle values.
2. Since my site's registrants have to be approved by an admin, I need to send emails to the admins to let them know someone has asks to register. So, this module adds an administration form field where you can enter the admin emails that need to be notified someone is requesting membership.

I haven't fully documented the code and I'm pretty sure I never will. Below is the code for both the modifyMail.info file and modifyMail.module file.

modifyMail.info is as follows:

; $Id$
name = Modify Mail
description = The modfiyMail module adds variables available to the system-generated emails.
core = 6.x

modifyMail.module is as follows:


/**
* Version: Drupal 6.x
*
* Implementation of hook_form_alter()
* Alter the user_admin_settings form to display the added email tokens
**/

function modifyMail_form_alter(&$form, $form_state, $form_id){

	if ($form_id == "user_admin_settings") { 
		$form['email']['pending_approval']['#description'] .= ' Additional variables are: !first, !middle, !last.';
	}

}







/**
* Implementation of hook_mail_alter().
*
* This hook is being used to get the full name of the registrant and replace
* the variables within emails (!first, !middle, !last) with the registrant's
* first, middle and last name as captured by the registration form and stored
* in profiles_values table.
*
* NOTE: Remember to add the new variables (!first, !middle, !last) to the email subject line and body in
* administration section > user settings > User e-mail settings > Welcome...
*/

function modifyMail_mail_alter(&$message) {
global $base_root;
global $base_path;
global $user;


	switch($message['id']) {





		case 'user_status_activated':
			//NOTIFY ADMINS OF ACCOUNT ACTIVATION
			$bcc = variable_get('modifyMail_addresses', '');
			if ($bcc != '') $message['headers']['bcc'] = $bcc;

			break;





		case 'user_register_pending_approval_admin':
			//get new registrant's username and id
			$sql2 = 'SELECT uid,name FROM {users} WHERE uid=(SELECT MAX(uid) FROM {users})';
			$result2 = db_query($sql2);
			$row2 = db_fetch_object($result2);
			
			$uid = $row2->uid;
			$name = $row2->name;
			
			//get new registrant's fullname name
			//get the profile fields using user id
			$sql = "SELECT fid,value FROM {profile_values} WHERE uid='%s' AND (fid=1 OR fid=2 OR fid=3)";
			$result = db_query($sql, $uid);
			
			//create array to hold values
			$new_variables = array();
	
			//loop through query result
			while ($row = db_fetch_object($result)) {
				//switch on the field id (fid) of the result
				//fid 1 is first name, fid 2 is last name, fid 3 is middle name
				switch ($row->fid) {
					case 1:
						$new_variables += array('!first' => $row->value);
						break;
					case 2:
						$new_variables += array('!last' => $row->value);
						break;
					case 3:
						$new_variables += array('!middle' => $row->value);
						break;			
				}
			}
			//check the middle name and tweak for full name display
			if (isset($new_variables['!middle'])) {
				$new_variables['!middle'] .= " ";
			}else{
				$new_variables['!middle'] = '';
			}
			
			//create array of replacement vars
			$replace = array(
						'!fullname' => $new_variables['!first'] . " " . $new_variables['!middle'] . $new_variables['!last'],
						'!site'		=> variable_get('site_name', 'Your Site Name'),
						'!username'	=> $name
			);
			
			$email_list = variable_get('modifyMail_addresses', variable_get('site_mail',ini_get('sendmail_from')));

			
			$message['subject'] = _user_mail_text('pending_approval_admin_subject', $message['language'], $variables);
			//drupal_set_message('message subject is:'.$message['subject']);

			$message['subject'] = strtr($message['subject'], $replace);
			$message['body'][0] = $replace['!fullname'] . " registered as username: " . $replace['!username'] . ". \n\nAuthorize the registration at: " . $base_root . $base_path . "user/" . $uid . "/edit \n\nReview ".$replace['!fullname'] . "'s profile at: ".$base_root.$base_path."user/".$uid;
			//drupal_set_message("fullname is:".$replace['!fullname']." and body is:".$message['body'][0]);
			$message['to'] = $email_list;
			
		break;






	
		default :
		
		//identify to whom the email is being sent
		$email = $message['to'];
		
		//get user id from db using email address
		$sql2 = "SELECT uid FROM {users} WHERE mail='%s'";
		$result2 = db_query($sql2, $email);
		$row2 = db_fetch_object($result2);
		
		$uid = $row2->uid;
		
		//get the profile fields using user id
		$sql = 'SELECT fid,value FROM {profile_values} WHERE uid=%d AND (fid=1 OR fid=2 OR fid=3)';
		$result = db_query($sql, $uid);
		
		//create array to hold values
		$new_variables = array();
		
		//loop through query result
		while ($row = db_fetch_object($result)) {
			//switch on the field id (fid) of the result
			//fid 1 is first name, fid 2 is last name, fid 3 is middle name
			switch ($row->fid) {
				case 1:
					$new_variables += array('!first' => $row->value);
					break;
				case 2:
					$new_variables += array('!last' => $row->value);
					break;
				case 3:
					$new_variables += array('!middle' => $row->value);
					break;			
			}
		}
	
		//check for middle name existence
		if (!isset($new_variables['!middle'])) { $new_variables['!middle'] = ''; }
	
		//replace placeholders (!first, !last, !middle) in email
		//with corresponding new variables
		$message['subject'] = strtr($message['subject'], $new_variables);
		$message['body'][0] = strtr($message['body'][0], $new_variables);
		
		break;


		
	}


}



/**
* Implementation of hook_help().
*
* Throughout Drupal, hook_help() is used to display help text at the top of
* pages. Some other parts of Drupal pages get explanatory text from these hooks
* as well. We use it here to provide a description of the module on the
* module administration page.
*/
function modifyMail_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      // This description is shown in the listing at admin/modules.
      return t('The modfiyMail module adds variables available to the system-generated emails.');
  }
}











/**
* Valid permissions for this module
* @return array An array of valid permissions for the modifyMail module
* Sets the permissions
*/

function modifyMail_perm() {
	return array('administer modifyMail');
}






/*
The following adds a field for entering admin emails
to notify that a new member is requesting registration.
These should be the emails of admins that can approve/deny the request
*/


function modifyMail_admin() {
	$form['modifyMail_addresses'] = array (
		'#type'				=> 'textarea',
		'#title'			=> t('Notify addresses'),
		'#default_value'	=> variable_get('modifyMail_addresses', variable_get('site_mail',ini_get('sendmail_from'))),
		'#description'		=> t('Enter each recipient’s email address on a new line or place a comma between addresses. The email addresses entered will receive new member registration notifications.'),
		'#required'			=> TRUE
	);
	return system_settings_form($form);
}





/*
If you want to notify admins or others that a new member is requesting registration
This adds the entry in the admin menu.
*/
function modifyMail_menu() {
	$items = array();
	
	$items['admin/settings/modifyMail'] = array(
		'title'					=> 'Modify Mail Settings',
		'description'			=> 'Modify recipient list for new member registration notifications.',
		'page callback'			=> 'drupal_get_form',
		'page arguments'		=> array('modifyMail_admin'),
		'access arguments'		=> array('access administration pages'),
		'type'					=> MENU_NORMAL_ITEM
		);

	return $items;
}







/*
Validates the entered admin email addresses
*/

function modifyMail_admin_validate($form, &$form_state) {
	$email_list = trim($form_state['values']['modifyMail_addresses']);

	if (!is_string($email_list)) {
		form_set_error('modifyMail_admin_addresses', t('You must enter only valid email addresses separated by commas or on a new line.'));
	}


	if (!empty($email_list)) {
		//check if email was entered as comma-delimited
		$found = strpos($email_list, ",");
		$pattern = '/(\s)*/i';

		if ( is_numeric($found) && ($found != 0) ) {
			//comma-delimited
			//remove any whitespace character including [ \t\n\r\f\v]
			//drupal_set_message('modifyMail_addresses is comma-delimited');
			$email_list = preg_replace($pattern, '', $email_list);
		}
		//no comma was found, check if return-delimited
		elseif( preg_match($pattern, $email_list) == 1 ) {
			//return-delimited
			//drupal_set_message('modifyMail_addresses is return-delimited');
			//replace any whitespace character with comma
			$email_list = preg_replace('/(\s)+/i', ',', $email_list);
		}
		//drupal_set_message('email_list is:'.$email_list);


		//check again, because we just tried to normalize to comma-delimited
		$found = strpos($email_list, ",");
		//if comma-delimited (i.e. more than one email address);
		if ( is_numeric($found) && ($found != 0) ) {
			//convert email address list to array
			$aEmail = explode(",", $email_list);
			
			for($i=0;$i<count($aEmail);$i++) {
				if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $aEmail[$i])){
					form_set_error('modifyMail_addresses', 'The email address you entered in the #'.($i+1).' spot is not formatted properly or contains illegal characters.');
				}
			}
		}else{
			//contains only one email address
			if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email_list)){
				form_set_error('modifyMail_addresses', 'The email address you entered is not formatted properly or contains illegal characters. Be sure to use only commas between addresses or place each address on a separate line.');
			}
		}

	}
	$form_state['values']['modifyMail_addresses'] = $email_list;
}








maartenvg’s picture

When the token-module accepts profile content, you could use the Mail Editor module: http://drupal.org/project/mail_edit which gives you the ability to edit every e-mail template with added token-support.

WorldFallz’s picture

not sure how it will affect the registration email but the http://drupal.org/project/realname module may be worth a look.

===
"Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime." - Lao Tzu
"God helps those who help themselves." - Ben Franklin
"Search is your best friend." - Worldfallz

mukesh.agarwal17’s picture

hey,

you can try the following link for the code snippet that can help you out, short and sweet, does exactly what we need..
http://www.innoraft.com/blog/use-profile-fields-tokens-user-emails-drupal

Mukesh Agarwal
www.innoraft.com

zany’s picture

See the token_registration_mails module for genuine Token support. This includes e.g. first/last name from profiles.