Search code examples
phplaravelgmailbase64

Laravel displaying base64 image


How can I send e-mail with attached image if I receive the data in base64 format?

Here is mail template:

<h1>You got mail from - {{$user->name}}</h1>

<h2>Date:</h2>
<p>{{$post->created_at}}</p>
<h2>Message:</h2>
<p>{{$post->body}}</p>

<img src="data:image/png;base64, {{$image}}">

<div>
</div>

And the logic:

public function createPost()
{
    $user = JWTAuth::toUser();
    $user->posts()->create(['user_id' => $user->id, 'body' => Input::get('comment.body')]);

    Mail::send('mail.template', [
        'image' => Input::get('image'),
        'user'  => $user,
        'post'  => Post::where('user_id', $user->id)->get()->last(),
    ], function ($m) use ($user) {
        $m->from('[email protected]', 'XYZ');

        $m->to('[email protected]', $user->name)->subject('Subject');
    });
}

From this I only get mail with full base64 string...img tag gets ignored


Solution

  • The solution I came up with is to save the image first in order to attach it as Viktor suggested although I don't have Laravel 5.3. so the method is somehow different.

    User may or may not send the picture, so the method is as follows:

    $destinationPath = null;
            if($request->has('image')){
                // save received base64 image
                $destinationPath = public_path() . '/uploads/sent/uploaded' . time() . '.jpg';
                $base64 = $request->get('image');
                file_put_contents($destinationPath, base64_decode($base64));
            }
    

    And then attach the saved image to the mail:

    Mail::send('mail.template', [
        'user'  => $user,
        'post'  => Post::where('user_id', $user->id)->get()->last(),
    ], function ($m) use ($user) {
        $m->from('[email protected]', 'XYZ');
    
        $m->to('[email protected]', $user->name)->subject('Subject');
    
        if($request->has('image')){
            $m->attach($destinationPath);
        }
    });
    

    The mail template:

    <h1>You got mail from - {{$user->name}}</h1>
    
    <h2>Date:</h2>
    <p>{{$post->created_at}}</p>
    <h2>Message:</h2>
    <p>{{$post->body}}</p>