来自字段的PHP发送邮件时()

I'm using PHP's mail() function and noticing that my mail is being shown from being sent by 'My Website' in my inbox, but when I click on the actual email it shows it being sent from mywebsite@sitename.localdomain.

Ideally I'd like to have it say being sent from 'My Website', but the reply email being 'no-reply@mywebsite.com', and not to have it say anything about @sitename.localdomain.

$to = trim(strtolower($_POST['to']));
$from = trim($_POST['from']);
$message = trim($_POST['message']);

$subject = $from . ' has shared a link with you';
$headers = 'From: My Website' . "
" .
        'Reply-To:' . $to . "
" .
        'X-Mailer: PHP/';


mail($to, $subject, $message, $headers);

Is this an issue that I need to fix in Apache, or can I modify the headers within PHP?

Try this:

$to = trim(strtolower($_POST['to']));
$from = trim($_POST['from']);
$message = trim($_POST['message']);

$subject = $from . ' has shared a link with you';
$headers = 'From: My Website <no-reply@mywebsite.com>' . "
" . // <- change your email here
        'Reply-To:' . $to . "
" .
        'X-Mailer: PHP/';


mail($to, $subject, $message, $headers);

The Question and Answer #1 contains a serious security vulnerability -

$to = trim(strtolower($_POST['to']));

Will allow an attacker to use your website to email arbitrary spam and your site will be blocked from most search engines. See https://www.owasp.org/index.php/Top_10_2010-A1

My recommendation is to

  • Sanitize the to and from fields
  • Never ever ever copy the message in the post to the output unless carefully sanitized.