Drupal/PhpMailer - Wrong "From" Name via Contact Form

If you are using Drupal 6 with PHPMailer configured, then you might notice that after receiving an email through the contact form the "From" field is populated with the site name, instead of the user name. This can cause problems, or at least be a nuisance, since clicking the reply button in your email will automatically populate the “To” field with your site’s name. If you try to change the setting through PHPMailer (admin/settings/phpmailer), an advanced option with a field called “From Name”, and a description that reads “Enter a name that should appear as the sender for all messages. If left blank the site name will be used instead” is as close as it gets.It turns out that PHPMailer will populate the From field correctly if it receives the email in the format “Name <email@test.com>”. Luckily, Drupal has a hook which lets you alter the email message before sending it, function hook_mail_alter. You can read more about it at http://api.drupal.org/api/function/hook_mail_alter/6.Within your custom module, you can invoke the mail_alter hook, verify the message is coming from the contact form, and if so alter the email address to the correct format. Here is my solution:
<?php
function MYMODULE_mail_alter(&$message) {
    switch (
$message['id']) {
        case 
'contact_page_mail':
        
// set Fromname to user
            
if(!empty($message['from']) && !empty($message['params']['name'])) {
                
$message['from'] = $message['params']['name'].' <'.$message['from'].'>';
            }
            break;
    }
}
?>
Note: You will need to change "MYMODULE" to the actual module name

Comments (3)

  1. Default avatar
    ( Guest ) 12 years ago 12 years ago
    This didn't work for me. My working function ended up like this:
    <?php
    function herk_site_mail_alter(&$message) {

      switch (
    $message['id']) {

        case 
    "user_register_admin_created":

        case 
    "user_register_no_approval_required"

        case 
    "user_register_pending_approval":

        case 
    "user_status_blocked":

        case 
    "user_status_deleted":

        break;

        case 
    "user_password_reset":

          
    $message['headers']['From'] = $message['from'] = $message['params']['name'].' <'$message['from'] .'>';

        break;

      }     

    }
    ?>


    You can replace $message['params']['name'] and $message['from'] with hard-coded values as well for each case if needed.
  2. Default avatar
    ( Guest ) 11 years ago 11 years ago
    Thanks seyi,

    You have saved my day to give such a basic information about sender name in email.
  3. Default avatar
    ( Guest ) 11 years ago 11 years ago
    I just created a patch for PHPmailer that should help fix this issue. Take a look at it here:
    http://drupal.org/node/1204594#comment-6473618