Sending email using Zend Framework and PHP

社会主义新天地 提交于 2019-11-30 14:23:49
Matt Way

I recommend you use Zend_Mail instead of mail(). It handles a lot of stuff automatically and just works great.

Do you have a SMTP server? Trying to send mail without your own SMTP server could be causing the mail to not be sent.

This is what I use for sending mails using Zend_Mail and Gmail:

In Bootstrap.php, I configure a default mail transport:

protected function _initMail()
{
    try {
        $config = array(
            'auth' => 'login',
            'username' => 'username@gmail.com',
            '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
    }
}

Then to send an email I use the following code:

//Prepare email
$mail = new Zend_Mail();
$mail->addTo($email);
$mail->setSubject($subject);
$mail->setBody($message);
$mail->setFrom('username@gmail.com', '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.
}

First of all i would switch to using Zend_Mail. Second i would use a real mail account on an smtp server somewhere and send from that. A lot of times there are restrictions on sending from the server itself, but using an actual mail server usually fixes this.

There's a very useful screencast covering Zend_Mail available on ZendCasts http://www.zendcasts.com/introduction-to-zend_mail/2010/02/

Hayk Manasyan

In line $mail->setBody($message);, change it to $mail->setBodyText($message);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!