K
K
kiranananda2018-08-23 08:35:00
Laravel
kiranananda, 2018-08-23 08:35:00

Laravel mail inline img?

Good afternoon!
I am sending emails via laravel. But my template is set through the admin panel, and not through the view. Further in the code, I check the pictures inside the message, replace them with inline and send. I use this code for this:

$this->withSwiftMessage(function ($message) use  ($msg) {
    $message->setBody (preg_replace_callback("|<img.*?data-id=[\'\"]{1}(\d+)[\'\"]{1}.*?>|", function ($matches) use ($message) {
        $img = $matches[0];
        $imgId = $matches[1];

        if (($imgObj = \Backend\Root\Upload\Models\MediaFile::find($imgId))) {
            $sizes = 'orig';               
            if (preg_match('/width=[\'\"]{1}(\d+)[\'\"]{1}/', $img, $width) && preg_match('/height=[\'\"]{1}(\d+)[\'\"]{1}/', $img, $height)) {
                $sizes = \Backend\Root\Upload\Services\Uploads::sizesToStr([ $width[1], $height[1] ]);
            }

            if (isset($imgObj['sizes'][$sizes])) {
                $fName = $message->embed(new \Swift_Image(
        Storage::disk($imgObj->disk)->get($imgObj->path.$imgObj['sizes'][$sizes]['path'].$imgObj['sizes'][$sizes]['file']), $imgObj['orig_name'])
                );

                $img = preg_replace("/src=[\'\"]{1}.*?[\'\"]{1}/", "src=\"".$fName."\"", $img);
            }
        }

        return $img;
    }, $msg ), 'text/html' );
});

But the fact is that the $message->setBody method refuses to work, because in Laravel in the Mailer class the send method is done like this
call_user_func($callback, $message);
$this->addContent($message, $view, $plain, $raw, $data);

And the addContent function overrides my setBody call from the callback function.
Of course, you can implement all this code in a template, but this is somehow not correct. And how to implement it correctly? If I comically $this->addContent method everything works fine...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kiranananda, 2018-08-25
@kiranananda

The solution is still found on the Internet :). You need to call the code $this->view([], []); at the end. Then the $message->setBody() function will start working. I don’t know how much this is generally documented somewhere and whether the developers will break this code in the future, but so far it works :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question