Ad

Send Email From A Separated File Using Swift Mailer

- 1 answer

With Laravel Mailer we can send email from a separated file. We mentioned the file name as a first parameter of send() function. As an example:

Mail::send('emails.billRequest',$data, function($message){
    // rest of code
});

In above example emails.billRequest is the file name I want to send. This process is working fine with me, no problem with that.

My Problem is

Currently I am using Swift Mailer. My code is:

$transport = \Swift_SmtpTransport::newInstance('smtp.email.com',587,'tls')
    ->setUsername('[email protected]')
    ->setPassword('mypassword');

$mailer = \Swift_Mailer::newInstance($transport);

$message = \Swift_Message::newInstance('test subject')
    ->setFrom(['[email protected]'=>'sender'])
    ->setTo(['[email protected]'=>'reciver'])
    ->setBody('<p>this is a test body</p>','text/html');

$result = $mailer->send($message);

This code also working perfectly. My question is, is there any way to keep my email's body in a separated file?

Writing a long html email inside setBody() will look messy.

Ad

Answer

No problem with that.

Instead of:

->setBody('<p>this is a test body</p>','text/html');

use

->setBody(view('emails.billRequest', $data)->render());

Construction:

view('emails.billRequest', $data)->render()

will generate your Blade file emails/billRequest.blade.php and pass $data to template and render it into string so you can now use it as e-mail body

EDIT

OF course If I were you, I would reconsider using SwiftMailer directly when it's not really needed.

Ad
source: stackoverflow.com
Ad