Laravel:如何排队邮件以便稍后发送

时间:2014-05-07 04:48:49

标签: php laravel queue sendmail

我试图使用Mail ::队列发送和发送电子邮件,但是当我调用此函数时,它简单地发送邮件,并且响应被延迟...我认为使用Mail :: queue的重点是队列......

我希望即时回复,而不必等待发送电子邮件

例如

Mail::queue('emails.template', $data, function($message) {
    $message->to('somemail@gmail.com');
    $message->subject('Notificacion');
});

return Response::json(array('error' => 0, 'message' => 'Ok'));

我希望在不等待邮件发送的情况下收到回复。 我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

您使用的是什么队列驱动程序(app/config/queue.php - 'default' param)?如果您正在使用sync,并且未设置其中一个,那么您将使用同步驱动程序,该驱动程序完全符合名称所示:将排队的任务运行为创建任务后立即。

您需要为Laravel配置MQ服务器以进行通信。你可以获得一个免费的iron.io帐户,然后你需要配置它,例如:

'iron' => array(
    'driver'  => 'iron',
    'project' => 'iron-io-project-id',
    'token'   => 'iron-io-queue-token',
    'queue'   => 'queue-name',
),

然后当你使用Mail::queue()时,它会将指令推送到iron.io.然后,您必须让另一个线程侦听队列 - 只需运行php artisan queue:listen并在消息被推送到队列时保持运行。

答案 1 :(得分:-1)

 /**
 * Get all email recipients and include their user details for Mailgun's
 * template tags - %recipient.userToken%
 */
private function getRecipients()
{
    foreach (User::get() as $user)
    {
        $this->recipients[$user->email] = [
            'id' => $user->id,
            'userToken' => $user->user_token,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email
        ];
    }
}

private function sendEmail()
{
    $subject = 'Demo Subject';
    /**
     * Data for the Blade template
     */
    $data = [
        'foo' => 'bar'
    ];
    // Inline the CSS for the email
    $inliner = new InlineEmail('emails.some-email', $data);
    $content = $inliner->convert();

    // Create Emails table entry for this email. Used for Mailgun webhooks
    $email = Email::create(['user_id' => $this->userId, 'subject' => $subject, 'email_id' => str_random()]);

    // Prepare the email addresses
    $emailAddresses = array_column($this->recipients, 'email');

    $this->mailgun->sendMessage('demo.org', [
        "from" => 'support@demo.org',
        "to" => implode(',', $emailAddresses), // Comma separated list of email addresses
        "subject" => $subject,
        "html" => $content, // Inlined CSS HTML from Blade
        "text" => "Plain text message here",
        "recipient-variables" => json_encode($this->recipients), // Required for batch sending, matches to recipient details
        "v:messageId" => $email->id, // Custom variable used for webhooks
    ]);
}