Swiftmailer发送后删除附件

时间:2013-03-26 16:58:32

标签: php symfony swiftmailer

我尝试在发送带有 Symfony 2.1 Swiftmailer 的电子邮件后删除附件文件,但如果我在返回响应对象(重定向)之前删除了该文件,电子邮件不发送。

我想这是因为symfony会在回复中发送电子邮件,因此当电子邮件发送时,附件已经被删除。

例如:

<?php

// DefaultCotroller.php

$message = \Swift_Message::newInstance($subject)
    ->setFrom('no-reply@dasi.es')
    ->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来清理文件,但我不想使用它。

谢谢!

3 个答案:

答案 0 :(得分:10)

您可以在此处查看处理内存假脱机的代码: 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 :(得分:2)

我不确定,但是消息假脱机可能会导致此问题。在SF2中,默认使用内存假脱机,这意味着消息是在内核终止事件上发送的。

因此,您必须在删除文件之前清空假脱机。

如果这是您的问题的原因,请在此处查找解释良好的解决方案: http://sgoettschkes.blogspot.de/2012/09/symfony-21-commands-and-swiftmailer.html

答案 2 :(得分:0)

为了完成james_t的非常好的答案,如果您使用multiple mailers,则需要进行一些更改。

替换

//  Default mailer
$mailer = $this->container->get('mailer');

$subject  = '...';
$from     = '...';
$to       = '...';
$body     = '...';

$message = \Swift_Message::newInstance()
    ->setSubject($subject)
    ->setFrom($from)
    ->setTo($to)
    ->setBody($body, 'text/html')
;

//  Put e-mail in spool
$result = $mailer->send($message);

//  Flush spool queue
$transport      = $mailer->getTransport();  
$spool          = $transport->getSpool();
$realTransport  = $this->container->get('swiftmailer.transport.real')
$spool->flushQueue($realTransport);

通过

//  Custom mailer
$mailerServiceName  = 'myCustomMailer';
$customMailer       = $this->container->get("swiftmailer.mailer.".$mailerServiceName);

$subject  = '...';
$from     = '...';
$to       = '...';
$body     = '...';

$message = \Swift_Message::newInstance()
    ->setSubject($subject)
    ->setFrom($from)
    ->setTo($to)
    ->setBody($body, 'text/html')
;

//  Put e-mail in spool
$result = $customMailer->send($message);

//  Flush spool queue
$transport      = $customMailer->getTransport();  
$spool          = $transport->getSpool();
$realTransport  = $this->container->get('swiftmailer.mailer.'.$mailerServiceName.'.transport.real');
$spool->flushQueue($realTransport);