【问题标题】:Sending e-mail in Laravel with custom HTML在 Laravel 中使用自定义 HTML 发送电子邮件
【发布时间】:2018-07-04 18:06:25
【问题描述】:

我需要发送电子邮件,但我已经生成了 HTML,我不想使用 laravel Blade,因为我需要将 CSS Inliner 应用到 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,我该怎么做?

【问题讨论】:

    标签: php email laravel


    【解决方案1】:

    如果我在你想要实现的目标上是正确的,为了解决这个问题,我创建了一个名为 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!'); });

    让我知道你过得怎么样。

    【讨论】:

    • 此方法在使用单独的页眉页脚等时也可以与模板一起使用,效果也很好。
    【解决方案2】:

    我想分享一个提示,它可能有助于在没有“刀片”的情况下发送电子邮件。

    Laravel Mail 函数实际上是 Swift 的包装器。 只需将空数组分配给 $template 和 $data,我的意思是函数的前 2 个参数,然后在回调中执行其余的操作。

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

    【讨论】:

      【解决方案3】:

      无法从闭包中访问主体。

      您可以手动创建 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);
      

      【讨论】:

      • 你能谈谈“你的交通工具”是什么样的吗?
      【解决方案4】:

      在你的控制器中:

      Mail::to("xyz.gmail.com")->send(new contactMailAdmin($userData));
      

      【讨论】:

        【解决方案5】:
        $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!' );
         });
        

        【讨论】:

          猜你喜欢
          • 2021-01-05
          • 2020-04-16
          • 1970-01-01
          • 2020-02-01
          • 2015-01-30
          • 2016-11-03
          • 1970-01-01
          • 1970-01-01
          • 2015-08-24
          相关资源
          最近更新 更多