我建议你使用Zend_Mail
代替mail()
。它会自动处理很多事情并且效果很好。
您有 SMTP 服务器吗?尝试在没有您自己的 SMTP 服务器的情况下发送邮件可能会导致邮件无法发送。
这就是我用来发送邮件的方法Zend_Mail
和 Gmail:
In Bootstrap.php
,我配置默认邮件传输:
protected function _initMail()
{
try {
$config = array(
'auth' => 'login',
'username' => '[email protected]',
'password' => 'password',
'ssl' => 'tls',
'port' => 587
);
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($mailTransport);
} catch (Zend_Exception $e){
//Do something with exception
}
}
然后,要发送电子邮件,我使用以下代码:
//Prepare email
$mail = new Zend_Mail();
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setBody($message);
$mail->setFrom('[email protected]', 'User Name');
//Send it!
$sent = true;
try {
$mail->send();
} catch (Exception $e){
$sent = false;
}
//Do stuff (display error message, log it, redirect user, etc)
if($sent){
//Mail was sent successfully.
} else {
//Mail failed to send.
}