Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send raw mail via queue Laravel

For testing purpose, I want to send raw mail via Queue.

I can send a raw mail like this:

Mail::raw('bonjour', function($message) {
   $message->subject('Email de test')
           ->to('[email protected]');
});

But is there a way to send a raw mail via Queue (without creating a View nor Mailable)?

like image 524
rap-2-h Avatar asked Jan 15 '18 11:01

rap-2-h


People also ask

How do I send an email in laravel?

Laravel provides a clean, simple email API powered by the popular Symfony Mailer component. Laravel and Symfony Mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail , allowing you to quickly get started sending mail through a local or cloud based service of your choice.


1 Answers

I searched the past days without any outcome to accomplish exact this: a raw mail that can be queued.

Unfortunately I didn't found a solution without using Mailables and Views.

I assume you have the same reason as me: You want to send a 100% dynamically generated Mail from a string.

My solution was:

  1. creating a view that only contains one variable: <?php echo $content;
  2. create a mailable, passing the content to the constructor and set it to $this->content
  3. copy everything inside the old mail-closure into the build-method of the mailable and replace every $message-> with $this
  4. queue it ;)

public function send(Request $request) {
    $to = "[email protected]";
    $subject = "email de test";
    $content = "bonjour";
    Mail::send(new RawMailable($to, $subject, $content));
}

view (/ressources/view/emails/raw.blade.php):

{!! $content !!}

mailable:

<?php

namespace App\Mail;

use Dingo\Api\Http\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class RawMailable extends Mailable
{
    use Queueable, SerializesModels, ShouldQueue;

    private $mailTo;
    private $mailSubject;
    // the values that shouldnt appear in the mail should be private

    public $content;
    // public properties are accessible from the view

    /**
     * Create a new message instance.
     *
     * @param LayoutMailRawRequest $request
     */
    public function __construct($to, $subject, $content)
    {
        $this->content = $content;
        $this->mailSubject = $subject;
        $this->mailTo = $to;
    }

    /**
     * Build the message.
     *
     * @throws \Exception
     */
    public function build()
    {
         $this->view('emails.raw');

         $this->subject($this->mailSubject)
              ->to($this->mailTo);
    }
}
like image 91
Dennis Richter Avatar answered Oct 28 '22 15:10

Dennis Richter