使用 Swift Mailer 从单独的文件发送电子邮件
Send email from a separated file using Swift Mailer
使用 Laravel Mailer 我们可以从一个单独的文件发送电子邮件。我们提到文件名是 send()
函数的第一个参数。例如:
Mail::send('emails.billRequest',$data, function($message){
// rest of code
});
在上面的例子中emails.billRequest
是我要发送的文件名。这个过程对我来说很好,没问题。
我的问题是
目前我正在使用Swift Mailer
。我的代码是:
$transport = \Swift_SmtpTransport::newInstance('smtp.email.com',587,'tls')
->setUsername('myemailaddress@email.com')
->setPassword('mypassword');
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance('test subject')
->setFrom(['sender@email.com'=>'sender'])
->setTo(['reciver@email.com'=>'reciver'])
->setBody('<p>this is a test body</p>','text/html');
$result = $mailer->send($message);
此代码也能完美运行。我的问题是,有没有什么办法可以将我的电子邮件正文保存在一个单独的文件中?
在 setBody()
里面写一封很长的 html 电子邮件会显得很乱。
没问题。
而不是:
->setBody('<p>this is a test body</p>','text/html');
使用
->setBody(view('emails.billRequest', $data)->render());
施工:
view('emails.billRequest', $data)->render()
将生成您的 Blade 文件 emails/billRequest.blade.php
并将 $data
传递给模板并将其呈现为字符串,因此您现在可以将其用作电子邮件正文
编辑
当然如果我是你,我会重新考虑在不需要时直接使用 SwiftMailer
。
使用 Laravel Mailer 我们可以从一个单独的文件发送电子邮件。我们提到文件名是 send()
函数的第一个参数。例如:
Mail::send('emails.billRequest',$data, function($message){
// rest of code
});
在上面的例子中emails.billRequest
是我要发送的文件名。这个过程对我来说很好,没问题。
我的问题是
目前我正在使用Swift Mailer
。我的代码是:
$transport = \Swift_SmtpTransport::newInstance('smtp.email.com',587,'tls')
->setUsername('myemailaddress@email.com')
->setPassword('mypassword');
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance('test subject')
->setFrom(['sender@email.com'=>'sender'])
->setTo(['reciver@email.com'=>'reciver'])
->setBody('<p>this is a test body</p>','text/html');
$result = $mailer->send($message);
此代码也能完美运行。我的问题是,有没有什么办法可以将我的电子邮件正文保存在一个单独的文件中?
在 setBody()
里面写一封很长的 html 电子邮件会显得很乱。
没问题。
而不是:
->setBody('<p>this is a test body</p>','text/html');
使用
->setBody(view('emails.billRequest', $data)->render());
施工:
view('emails.billRequest', $data)->render()
将生成您的 Blade 文件 emails/billRequest.blade.php
并将 $data
传递给模板并将其呈现为字符串,因此您现在可以将其用作电子邮件正文
编辑
当然如果我是你,我会重新考虑在不需要时直接使用 SwiftMailer
。