我无法使用 laravel-sendgrid-driver 传递自定义变量

问题描述

我使用 https://github.com/s-ichikawa/laravel-sendgrid-driver 添加了 sendgrid 支持 在我的 Laravel 8 中,但我在添加定义参数时遇到了问题。我在控制:

    public function banUser(Request $request)
    {
        $user_id = $request->user_id;
        $bannedUser = User::find($user_id);
        if ($bannedUser === null) {
            return response()->json(['message' => 'User # "' . $request->user_id . '" not found!'],HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
        }
        $site_home_url          = config('app.url');
        $bannedUser->ban_reason = $request->ban_reason;
        if(empty($bannedUser->ban_reason)) {
            $bannedUser->ban_reason= 'Ban em all';
        }
        $bannedUser->status     = false;
        $bannedUser->updated_at = \Carbon\Carbon::Now(config('app.timezone'));
        $support_signature                          = config('app.support_signature','');

        try {
            $bannedUser->save();
            $additiveVars= [ // Additive Vars I want to see in my email view
                'site_home_url'            => $site_home_url,'to_user_email'            => $bannedUser->email,'to_username'              => $bannedUser->full_name,'ban_reason'               => $bannedUser->ban_reason,'support_signature'        => $support_signature,];
            $site_name= config('app.APP_NAME');
            $subject= 'Your account at ' . $site_name . ' was banned ';

            \Mail
                ::to($bannedUser->email)
                ->send( new SendgridMail( 'emails/user_was_baned',$bannedUser->email,[],$subject,$additiveVars ) )
//                ->embedData( // if to uncomment these lines it does not work anyway
//                    ['custom_args'=>$additiveVars]
//                );

    }

我创建了自定义电子邮件对象:/app/Mail/SendgridMail.PHP

<?PHP

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Sichikawa\LaravelSendgridDriver\SendGrid;

class SendgridMail extends Mailable
{
    use Queueable,SerializesModels;
    use SendGrid;

    /**
     * Create a new message instance.
     *
     * @return void
     */

    private  $m_view_name;
    private  $m_to_email_address;
    private  $m_ccEmailAddressList;
    private  $m_subject_text;
    private  $m_additiveVars;
    private  $m_attachFiles;

    public function __construct( string $view_name,string $to,array $cc= [],string $subject= '',array $additiveVars= [],array $attachFiles= [] )
    {
        $this->m_view_name= $view_name;
        $this->m_to_email_address= $to;
        $this->m_ccEmailAddressList= $cc;
        }
        $this->m_subject_text= $subject;


        $additiveVars['site_home_url']      = \Config::get('app.url');
        $additiveVars['site_name']          = \Config::get('app.name');
        $additiveVars['mail_from_address']  = \Config::get('app.MAIL_FROM_ADDRESS');
        $additiveVars['mail_from_name']     = \Config::get('app.MAIL_FROM_NAME');
        if ( $this->m_is_debug ) {
            echo '<pre>$additiveVars::' . print_r($additiveVars,true) . '</pre>';
        }
        $this->m_additiveVars= $additiveVars;
        $this->m_attachFiles= $attachFiles;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build( )
    {
        \Log::info(  varDump($this->m_additiveVars,' -1 build $this->m_additiveVars::') );  // I check list of Additive Vars as I expect 
        $mailObject= $this
            ->view( $this->m_view_name )
            ->subject( $this->m_subject_text )
            ->to( [$this->m_to_email_address] )
            ->cc( $this->m_ccEmailAddressList )
            ->with( $this->m_additiveVars )  // I send list of Additive Vars as into view
            ->sendgrid( $this->m_additiveVars );

        foreach( $this->m_attachFiles as $next_attach_file) {
            if ( file_exists($next_attach_file) ) {
                $mailObject->attach($next_attach_file);
            }
        }
        return $mailObject;

    }
}

和 resources/views/emails/user_was_baned.blade.PHP:

<!DOCTYPE html>
<html>
<head>
    <Meta charset="UTF-8">
</head>
<body>
<div class="wrapper">

    <h4 class="email_title">
        Hello,{{ $to_username }}
    </h4>

    <p class="email_title">You were baned at <a href="{{ $site_home_url }}" target="_blank" class="a_link">{{ $site_name }}</a> site !</p>

    <p class="email_subtitle">Now you can not login under your credentials :<br>
        User's email : {{ $to_user_email }}<br>
        Ban reason : {{ $ban_reason }}
    </p>

    <p class="email_footer">{!! $support_signature !!}</p>

</div>
</body>
</html>

但我遇到了如下错误

{"message":"User \"29\" not banned : Client error: POST https://api.sendgrid.com/v3/mail/sendresulted in a400 错误请求response:\n{\"errors\":[{\"message\":\"Additional property site_name is not allowed.\",\"field\":\"site_name\",\"help\":null},{\"message\":\"Addit (truncated...)\n"} 要么: {"message":"User \"29\" not banned : Client error: POST https://api.sendgrid.com/v3/mail/sendresulted in a400 错误请求response:\n{\"errors\":[{\"message\":\"Additional property mail_from_address is not allowed.\",\"field\":\"mail_from_address\",{ (truncated...)\n"}

或: {"message":"User \"29\" not banned : Client error: POST https://api.sendgrid.com/v3/mail/sendresulted in a400 错误请求response:\n{\"errors\":[{\"message\":\"Additional property to_user_email is not allowed.\",\"field\":\"to_user_email\",{\"message (truncated...)\n"} 要么: {"message":"User \"29\" not banned : Client error: POST https://api.sendgrid.com/v3/mail/sendresulted in a400 错误请求response:\n{\"errors\":[{\"message\":\"Additional property site_home_url is not allowed.\",\"field\":\"site_home_url\",{\"message (truncated...)\n"}

或: {"message":"User \"29\" not banned : Client error: POST https://api.sendgrid.com/v3/mail/sendresulted in a400 错误请求response:\n{\"errors\":[{\"message\":\"Additional property to_user_email is not allowed.\",{\"message (truncated...)\n"} 但是这些错误中的任何一个都是不同的,看起来任何下一个请求都会引发不同的错误(下一个) 模板中的 var。

为什么会出错以及如何修复?

        "laravel/framework": "^8.12","s-ichikawa/laravel-sendgrid-driver": "^3.0",

谢谢!

解决方法

您不需要添加另一个包。您可以只使用 SMTP。这样做的好处是您也可以遵循 Laravel 文档。要设置 SendGrid SMTP 配置,应在您的 .env 文件中添加/更新此配置:

MAIL_MAILER=smtp
# MAIL_DRIVER=smtp # for laravel < 7
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=sendgrid_api_key
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="John Smith"
MAIL_FROM_ADDRESS=from@example.com