How to show only the name instead of the email address of the sender in a simple php mail script

I have a simple php mail script which will send emails.

The problem is while sending it is displaying sendername <[email protected]>

I have given in the code as $headers = "From: $name <$senderEmail>";

I want to display only name and not email address of the sender.

How do I do that?

Here is the program in its entirety.

<?php

if($_POST["submit"]) {
    $recipient=$_POST["senderemail"];
    $subject=$_POST["subject"];
    $name=$_POST["name"];
    $senderEmail=$_POST["email"];
    $city=$_POST["city"];
    $headers = "From: $name <$senderEmail>";
    $mailBody="$city\n";
    $process=explode(",",$recipient);
    reset($process);

    foreach ($process as $to) {
        mail($to,$subject, $mailBody,$headers);
    }

    $thankYou="<p>Thank you! Your Message has been sent.</p>";
    echo 'Thank you! Your Message has been sent.';
}
?>

Upvotes: 2

Views: 3296

Answers (2)

tripleee
tripleee

Reputation: 189397

Your generated message already seems to contain the user's full name in the From: header (assuming $name is the human-readable name). How this is displayed by any individual user agent is no longer in your hands. Very often, it will display both parts regardless; or only shorten to the human-readable name if the sender's email address is in the recipient's address book. (Thunderbird takes this a step further and displays the information from the address book rather than the actual information in the message!)

One common problem is if the generated message has a different Sender: header; often, this will cause the recipient's user agent to display more than just the usual full name. Your question doesn't mention this, nor does it show one of the generated messages; but perhaps this will help you find a solution.

Upvotes: 2

Synchro
Synchro

Reputation: 37730

A From header containing both name and address should be formatted like this:

From: User Name <[email protected]>

If you don't provide a name, it will display the email address.

PHPMailer has built-in support for creating this header correctly for you via the From and FromName properties, and the setFrom method (it doesn't matter which you use):

$mail->setFrom('user@example/com', 'User Name');

or

$mail->From = 'user@example/com';
$mail->FromName = 'User Name';

Upvotes: 2

Related Questions