简体   繁体   中英

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 <senderemail@domain.com>

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.';
}
?>

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.

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

From: User Name <user@example.com>

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM