2013-03-26 39 views
3

我試圖用Symfony的2.1發送電子郵件Swiftmailer後刪除附件文件,但如果我返回響應對象(重定向)之前刪除的文件,電子郵件不會發送。Swiftmailer刪除附件後發送

我想這是因爲symfony在響應中發送電子郵件,所以當電子郵件發送時,附件已被刪除。

例如:

<?php 

// DefaultCotroller.php 

$message = \Swift_Message::newInstance($subject) 
    ->setFrom('[email protected]') 
    ->setTo($emails_to) 
    ->setBody($body, 'text/html') 
    ->attach(\Swift_Attachment::fromPath('backup.rar')); 

$this->get('mailer')->send(); 

unlink('backup.rar'); // This remove the file but doesn't send the email! 

return $this->redirect($this->generateUrl('homepage')); 

一種選擇是創建一個crontab來清理文件,但我不喜歡使用它。

謝謝!

回答

7

你可以看一下那個進程的內存線軸這裏的代碼: https://github.com/symfony/SwiftmailerBundle/blob/master/EventListener/EmailSenderListener.php

這是用來批量要發送的電子郵件。

您可以將send()電話後,你的unlink()調用之前添加此模仿發送電子郵件

 $transport = $this->container->get('mailer')->getTransport(); 

     $spool = $transport->getSpool(); 

     $spool->flushQueue($this->container->get('swiftmailer.transport.real')); 
+1

謝謝!這完美的作品:) – Erioch 2013-03-26 17:45:04

2

我不確定,但消息緩衝池可能會導致此問題。在SF2中,默認使用內存假脫機,這意味着消息正在內核終止事件上發送。

因此,在刪除文件之前,您必須先清空卷軸。

如果這是你的問題的原因,看看這裏的一個很好的解釋解決方案: http://sgoettschkes.blogspot.de/2012/09/symfony-21-commands-and-swiftmailer.html

+0

感謝實況還的行爲! – Erioch 2013-03-26 17:45:51