【发布时间】:2016-01-05 19:44:28
【问题描述】:
我创建了一个类来简化 mail() 的使用(可以添加附件、在文本和 html 模式之间切换等)。
我目前正面临这个问题:
- 当我尝试从本地服务器 (xampp) 发送邮件时,一切正常。
- 当我尝试从 真实 apache 服务器发送邮件时,邮件已正确发送,但 内容为空。不过,其他一切都很好(发件人、收件人、抄送...)。
从关于此类问题的SO问题中,我认为它与CRLF有关,但我无法确切找到问题所在(并且没有一个SO问题有帮助)。
这是我如何使用它的示例:
<?php
$mail = new Mail();
$mail->from('** adress **', '** name **');
$mail->addTo($user->mail);
$mail->addCC('** CC adress **', '** name **');
$mail->html = true;
$mail->subject = '** subject of the mail **';
$mail->content = '** HTML code **'; // This HTML is valid
$mail->send();
这是课程:
<?php
define('CRLF', "\r\n");
// This is used to send mail
class Mail extends Controller
{
// Boundary
private $boundary = null;
// Recipients, RFC 2822
public $to = [];
// Subject of the mail, RFC 2047
public $subject = '';
// Content of the mail
public $message = '';
// Content is HTML ?
public $html = false;
// Attachments
public $attachments = [];
// Additional headers
public $headers = [];
public function __construct()
{
$this->boundary = '_'.md5(uniqid(rand())).'_';
$this->headers = [
'MIME-Version' => '1.0',
'Content-Type' => 'multipart/mixed; boundary="'.$this->boundary.'"'
];
}
public function addTo($mail, $name = null)
{
$this->to[] = ($name ? $name.' ' : '').'<'.$mail.'>';
return $this;
}
public function from($mail, $name = null)
{
$this->headers['From'] = ($name ? $name.' ' : '').'<'.$mail.'>';
return $this;
}
public function replyTo($mail, $name = null)
{
$this->headers['Reply-to'] = ($name ? $name.' ' : '').'<'.$mail.'>';
return $this;
}
public function addCC($mail, $name = null)
{
$this->headers['Cc'][] = ($name ? $name.' ' : '').'<'.$mail.'>';
return $this;
}
public function addBC($mail, $name = null)
{
$this->headers['Bcc'][] = ($name ? $name.' ' : '').'<'.$mail.'>';
return $this;
}
public function addAttachment($fileName, $name = null)
{
$this->attachments[] = [$fileName, ($name === null ? pathinfo($fileName, PATHINFO_FILENAME) : $name)];
return $this;
}
public function send()
{
// Add main content
$fullMessage = '--'.$this->boundary.CRLF.
'Content-Type: '.($this->html ? 'text/html' : 'text/plain').'; charset=UTF-8'.CRLF.CRLF.
$this->content;
// Attachments
foreach ($this->attachments as $attachment)
{
if (!is_readable($attachment[0]))
throw new Exception('Cannot read file "'.$attachment[0].'"');
$fullMessage .= CRLF.CRLF.'--'.$this->boundary.$thids->nl.
'Content-Type: '.mime_content_type($attachment[0]).'; name="'.$attachment[1].'"'.CRLF.
'Content-Transfer-Encoding: base64'.CRLF.
'Content-Disposition: attachment; filename="'.$attachment[0].'"'.CRLF.CRLF.
chunk_split(base64_encode(file_get_contents($attachment[0]))).CRLF;
}
// Adding the headers
$fullHeaders = '';
foreach ($this->headers as $name => $content)
{
if (is_array($content))
$fullHeaders .= $name.': '.implode(', ', $content).CRLF;
else
$fullHeaders .= $name.': '.$content.CRLF;
}
return mail(implode(',', $this->to), utf8_decode($this->subject), $fullMessage, $fullHeaders);
}
}
【问题讨论】:
-
考虑检查您的测试和生产环境配置。也许php构建有区别