2013-03-27 126 views
3

我只是想知道如何檢查電子郵件是否已發送,或者何時在CakePHP中使用EmailComponent時失敗?CakePHP電子郵件組件檢查是否發送電子郵件

比如我目前使用這種方式:

$this->Email->from='<[email protected]>'; 
$this->Email->to='<[email protected]>'; 
$this->Email->sendAs='both'; 
$this->Email->delivery = 'debug'; 
$this->Email->send(); 
+2

爲了得到正確的答案,你總是* *需要提供您正在使用CakePHP的版本! – mark 2013-03-27 10:51:03

回答

10

$this->Email->send()應該返回true,如果它被成功發送。你可以嘗試這樣的:

if ($this->Email->send()) { 
    // Success 
} else { 
    // Failure 
} 

參考:

http://api.cakephp.org/2.3/class-EmailComponent.html

注:如果您使用CakePHP的2.x的,你可以嘗試使用CakeEmail類代替; EmailComponent已被棄用(Reference)。如果你使用1.x然後繼續。 :P

編輯:

如果你使用2.x的,你應該記住,CakeEmail(這是使用EmailComponent)可引發異常的意見如前所述,。您可以CakePHP itself或在一個try/catch折騰處理:

try { 
    if ($this->Email->send()) { 
     // Success 
    } else { 
     // Failure, without any exceptions 
    } 
} catch (Exception $e) { 
    // Failure, with exception 
} 
+1

這不應該需要一個try catch塊嗎?由於它可能會引發異常......文檔指出:「我們建議您使用try/catch來確保您的消息正確傳遞。」 – mark 2013-03-27 09:48:18

+0

@mark你能指出那個文檔嗎?你可能有一個有效的點,但我找不到。如果我查看源代碼,EmailComponent自身似乎不會自行拋出異常。 – thaJeztah 2013-03-27 10:39:53

+0

電子郵件組件只是包裝了CakeEmail的send()函數。因此它也會拋出異常,如果沒有正確捕捉,會產生很多麻煩。它也在這裏:http://book.cakephp.org/2.0/en/core-libraries/components/email.html – mark 2013-03-27 10:50:11