在Laravel中使用自定义HTML发送电子邮件


Sending e-mail in Laravel with custom HTML

我需要发送电子邮件,但我已经生成了HTML,我不想使用laravel刀片,因为我需要应用CSS内联到HTML,所以这就是我如何生成HTML:

getRenderedView($viewData) {
    //code
    $html =  View::make('email.notification', $viewData)->render();
    $this->cssInliner->setCSS($this->getCssForNotificationEmail());
    $this->cssInliner->setHTML($html);
    return $this->cssInliner->convert();
}

所以,要用Laravel发送邮件,你通常这样做:

Mail::send('emails.welcome', $data, function($message)
{
    $message->to('foo@example.com', 'John Smith')->subject('Welcome!');
});

但是我不想传递视图,我已经有了html,我该怎么做呢?

如果我是对的,你想要实现的,为了解决这个问题,我创建了一个名为echo.php的视图,里面只是echo $html。

把你的html赋值给$data['html']。

然后在下面传递$data['html']给echo视图。

Mail::send('emails.echo', $data, function($message) { $message->to('foo@example.com', 'John Smith')->subject('Welcome!'); });

让我知道你进展如何

我想分享一个技巧,可以帮助你在没有"刀片"的情况下发送电子邮件。

Laravel Mail函数实际上是Swift的包装器。把空数组赋值给$template和$data,我指的是函数的前两个参数,然后在回调中完成其余的。

Mail::send([], [], function($message) use($to, $title, $email_body)
{
    $message->setBody($email_body)->to($to)->subject($title);
});

不能从闭包访问body。

您可以手工创建swift消息:

    $message = 'Swift_Message::newInstance();
    $message->setFrom($messageToParse->template['fromEmail']);
    $message->setTo($messageToParse->to['email']);
    $message->setBody($messageToParse->body);
    $message->addPart($messageToParse->body, 'html contents');
    $message->setSubject('subject');

然后你需要创建传输:

    $mailer = self::setMailer( [your transport] );
    $response =  $mailer->send($message);

在你的控制器中:

Mail::to("xyz.gmail.com")->send(new contactMailAdmin($userData));
$data = array( 'email' => 'sample@domail.com', 'first_name' => 'Laravel', 
        'from' => 'sample@domail.comt', 'from_name' => 'learming' );
Mail::send( 'email.welcome', $data, function( $message ) use ($data)
{
 $message->to( $data['email'] )->from( $data['from'], 
 $data['first_name'] )->subject( 'Welcome!' );
 });