为什么我的PHP到SMTP邮件脚本不起作用?

时间:2014-12-02 15:07:35

标签: php html smtp sendmail smtpclient

我的机器上运行了一个本地sendmail实例,我正在使用php脚本发送自定义消息以运行内部匿名建议应用程序。 我目前使用以下脚本:

<?php
$to      = '*to*';
$subject = '*subject*';
$message = '*message*';
$headers = 'From: *from*' . "\r\n" .
    'Reply-To: *replyto*' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

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

我希望能够支持HTML,我认为这是以下内容:

<?php
$to      = '*to*';
$subject = '*subject*';
$message = '<html><a href="www.google.com">here</a></html>';
$headers = 'From: *from*' . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Contesnt-type:text/html;charset=UTF-8' . "\r\n";
$headers .= 'Reply-To: *replyto*' . "\r\n";

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

1 个答案:

答案 0 :(得分:0)

我是通过以下功能完成的:

private function plaintext_version($text) {

return "--PHP-nextpart-".$this->random_hash
     ."\nContent-Type: text/plain; charset=\"iso-8859-1\""
     ."\nContent-Transfer-Encoding: 7bit"
     ."\n$text";

} // EOF plaintext_version

private function HTML_version($html) {

return "--PHP-nextpart-".$this->random_hash."
Content-Type: text/html; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit

$html
";
} // EOF HTML_version

这是“发送”功能。 请注意,Content-Type是“multipart / alternative”,并且指定了“boundary”;我通过将“--PHP-nextpart-”与散列函数的输出连接来创建边界。

public function Send() {

  if (strlen($this->cc_to)) $this->headers .='Cc: '.$this->cc_to . "\r\n";

  if (strlen($this->bcc_to)) $this->headers .='Bcc: '.$this->bcc_to . "\r\n";

  if (strlen($this->reply_to)) $this->reply_to = $this->mail_from;


  $l_headers = 'From: '.$this->mail_from . "\r\n"
  .'Reply-To: '.$this->reply_to. "\r\n"
  .'X-Mailer: PHP/' . phpversion()."\r\n";

  if (strlen($this->headers)) $l_headers .= $this->headers;

  $l_headers .= "Content-Type: multipart/alternative; boundary=\"PHP-nextpart-".$this->random_hash."\"";

  $mess = $this->plaintext_version($this->msg_text) . "\n\n". $this->HTML_version($this->html_version);

  if (strlen($this->to_name)) {
     $to = "\"".$this->to_name."\" <".$this->mail_to.">";
  } else {
     $to = $this->mail_to;
  }

  $sent = mail($to,$this->subject,$mess,$l_headers);
  if ($sent) return true;
  return false;

} //EOF Send()