Laravel Framework, PHP & MySQL, Tutorials

Laravel storing mailables

Laravel's Mailable emails are perfect for sending rich HTML emails, there are times when you need to store the contents of an email being sent out.

Here's where things get tricky. When sending a mailable the default documented approach is to create a new instance inside the send() method.

Mail::to($to)->send(new SendAlert());

That makes sense since you can see the contents of an email by returning an instance of the mailable like this:

return new SendAlert();

That does not help us storing the email, well it actually does, you see when creating an instance of the mailable it does not render directly it needs to be returned in order to be executed. That's what the send() method does.

Looking over the Mailable class there is a method called render() which renders the email. This is perfect for our needs.

Going back to my earlier example lets now create a new instance inside send() and instead pass an instance.

$mailbody = new SendAlert();
Mail::to($to)->send($mailbody);

The email will still send and now we can store the contents by calling the render method on our object.

$body = $mailbody->render();

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.