使用 Zend Framework 和 PHP 发送电子邮件

2021-12-29 00:00:00 email php zend-framework send

我正在编写一个表单,当用户输入他们的电子邮件帐户并点击发送时,一封电子邮件将发送到他们的电子邮件帐户.

I working on a form whereby when the user enter in their email account and click on send, an email will be sent to their email account.

我已经解决了所有问题.只是它不会将电子邮件发送到我的帐户.有人有想法么?有没有我遗漏的配置之类的?

I have everything worked out. Just that it doesnt send the email to my account. Anyone have any ideas? Is there a configuration that I left out or something?

这是来自我的控制器的示例:

This is the sample from my controller:

public function retrieveemailAction(){

    $users = new Users();
    $email = $_POST['email'];                
    $view = Zend_Registry::get('view'); 

    if($users->checkEmail($_POST['email'])) {

        // The Subject
        $subject = "Email Test";

        // The message
        $message = "this is a test";            

        // Send email
        // Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
        // Use if command to display email message status
        if(mail($email, $subject, $message, $headers)) {
            $view->operation = 'true';
        }            
    } else {
         $view->operation = 'false';
    }

    $view->render('retrieve.tpl');
}

推荐答案

我建议您使用 Zend_Mail 而不是 mail().它可以自动处理很多东西,而且效果很好.

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

你有 SMTP 服务器吗?尝试在没有您自己的 SMTP 服务器的情况下发送邮件可能会导致邮件无法发送.

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

这是我使用 Zend_Mail 和 Gmail 发送邮件的方式:

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

Bootstrap.php中,我配置了一个默认的邮件传输:

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.
}

相关文章