检查邮件是否成功发送到Laravel 5

时间:2015-10-01 08:00:10

标签: laravel smtp laravel-5 sendmail

我有一个可以使用此

在Laravel5上发送邮件的功能
/**
 *  Send Mail from Parts Specification Form
 */
 public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) {
        $message->from('yourEmail@domain.com', 'Learning Laravel');
        $message->to('goper.zosa@gmail.com');
        $message->subject('Learning Laravel test email');
    });

    return redirect()->back();
 }

 /**
  * Return message body from Parts Specification Form
  * @param object $data
  * @return string
  */
 private function getMessageBody($data) {

    $messageBody = 'dummy dummy dummy dummy';
 }

并成功发送。但是如何检查它是否被发送?像

if (Mail::sent == 'error') {
 echo 'Mail not sent';
} else {
 echo 'Mail sent successfully.';
}

我只是猜测那段代码。

4 个答案:

答案 0 :(得分:18)

我不完全确定这会起作用,但你可以试一试

/**
 *  Send Mail from Parts Specification Form
 */
public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) {
        $message->from('yourEmail@domain.com', 'Learning Laravel');
        $message->to('goper.zosa@gmail.com');
        $message->subject('Learning Laravel test email');
    });

    // check for failures
    if (Mail::failures()) {
        // return response showing failed emails
    }

    // otherwise everything is okay ...
    return redirect()->back();
}

答案 1 :(得分:12)

  

希望这有帮助

Mail::failures()将返回一系列失败的电子邮件。

Mail::send(...)

if( count(Mail::failures()) > 0 ) {

   echo "There was one or more failures. They were: <br />";

   foreach(Mail::failures() as $email_address) {
       echo " - $email_address <br />";
    }

} else {
    echo "No errors, all sent successfully!";
}

来源:http://laravel.io/forum/08-08-2014-how-to-know-if-e-mail-was-sent

答案 2 :(得分:1)

您还可以使用“ Swift_TransportException”来识别任何错误。

try{

   //code to send the mail

}catch(\Swift_TransportException $transportExp){
  //$transportExp->getMessage();
}

答案 3 :(得分:0)

您可以为此使用Mail :: failures()函数。 如果存在,它将收集失败的邮件,因此您可以使用下面的代码进行检查。

public function sendMail(Request $request) {
    $data = $request->all();

    $messageBody = $this->getMessageBody($data);

    Mail::raw($messageBody, function ($message) use ($messageBody) {
        $message->from('yourEmail@domain.com', 'Learning Laravel');
        $message->to('goper.zosa@gmail.com');
        $message->subject($messageBody); 
    });

    // check for failed ones
    if (Mail::failures()) {
        // return failed mails
        return new Error(Mail::failures()); 
    }

    // else do redirect back to normal
    return redirect()->back();
}