You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP Net/SMTP.php发送邮件时发件人地址不显示问题求助

解决Net/SMTP发送邮件无发件人显示的问题

嘿,我仔细看了你的代码和遇到的问题——邮件能正常发送但收件箱显示无发件人,核心原因是你只在SMTP协议层面设置了发件人,但没有在邮件内容的头部添加From字段。邮件客户端(比如Yahoo邮箱)主要读取邮件内容里的头信息来显示发件人,所以才会出现这个情况。

具体修改步骤:

  • 首先,补充完整的邮件头信息,除了Subject,必须添加From字段,还可以加上Reply-To提升用户体验,同时指定编码避免乱码:
    // 构建完整的邮件头
    $headers = "From: " . $from . "\r\n";
    $headers .= "Reply-To: " . $from . "\r\n";
    $headers .= "Subject: Test Message\r\n";
    $headers .= "Content-Type: text/plain; charset=utf-8\r\n";
    
  • 然后,发送邮件时,要把邮件头和正文用两个换行符(\r\n\r\n)分隔开,这是邮件格式的标准要求:
    // 发送邮件内容:头 + 空行 + 正文
    if (PEAR::isError($smtp->data($headers . "\r\n\r\n" . $body))) {
        die("Unable to send data\n");
    }
    
  • 另外,确认你的虚拟主机(planethippo)允许gaborszita@gaborszita.tk作为发件人地址,不过你已经用这个地址做SMTP认证了,这部分应该没问题。

修改后的完整代码:

<?php 
ini_set("include_path", '/home/gaborszi/php:' . ini_get("include_path") ); 
echo htmlspecialchars($_POST['name']); 
require 'Net/SMTP.php'; 

$host = 'localhost'; 
$from = 'gaborszita@gaborszita.tk'; 
$rcpt = array('gaborszita@yahoo.com', 'gaborszita@gaborszita.tk'); 

// 构建完整邮件头
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: " . $from . "\r\n";
$headers .= "Subject: Test Message\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n";

$body = "Name: " . htmlspecialchars($_POST['name']); 

/* Create a new Net_SMTP object. */ 
if (! ($smtp = new Net_SMTP($host))) { 
    die("Unable to instantiate Net_SMTP object\n"); 
} 

/* Connect to the SMTP server. */ 
if (PEAR::isError($e = $smtp->connect())) { 
    die($e->getMessage() . "\n"); 
} 

$smtp->auth('gaborszita@gaborszita.tk','mypassword'); 

/* Send the 'MAIL FROM:' SMTP command. */ 
if (PEAR::isError($smtp->mailFrom($from))) { 
    die("Unable to set sender to <$from>\n"); 
} 

/* Address the message to each of the recipients. */ 
foreach ($rcpt as $to) { 
    if (PEAR::isError($res = $smtp->rcptTo($to))) { 
        die("Unable to add recipient <$to>: " . $res->getMessage() . "\n"); 
    } 
} 

/* Set the body of the message. */ 
if (PEAR::isError($smtp->data($headers . "\r\n\r\n" . $body))) { 
    die("Unable to send data\n"); 
} 

/* Disconnect from the SMTP server. */ 
$smtp->disconnect(); 
?>

关键说明:

SMTP协议里的mailFrom()设置的是信封发件人(主要用于处理退信),而邮件内容里的From头才是收件箱显示的发件人信息。两者都正确设置后,邮件客户端就能正常显示发件人了。

内容的提问来源于stack exchange,提问作者Gabor Szita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:23