Laravel: Issues in Thumbnails in Email Attachments

|
| By Webner

Laravel: Issues in thumbnail along with images while attaching multiple attachments to the mail

While sending an email to someone using a laravel Mailable class, we may need to attach some attachments to it. Then we can simply use the method attach of that class along with the message to send.

$message->attach($attachment->getRealPath());

It works fine with a single image or file. But when we try to attach multiple files, it creates an issue in thumbnails of the images in the mail.

For example:

$contact_us_email = ‘support@gmail.com’;				
Mail::send('mail.contact-us',
array(
		'name' => Auth::user()->name,
		'email' => Auth::user()->email,
		'subject' => $request->get('subject'),
		'user_message' => $request->get('message')
	), function($message) use ($request,$contact_us_email)
	{
		$attachments = $request->attachments;						
		if(is_array($attachments) && count($attachments)>0){
			foreach($attachments as $attachment){
				$message->attach($attachment->getRealPath());							
			}
		}
		$message->to($contact_us_email, 'Admin')->subject( $request->get('subject') );
	}
);

In the above code, we are sending an email to the person whose email is set in $contact_us_email variable. We are attaching multiple files with the message using the method attach() in the loop.

When we execute this code, it will send an email along with images to the email address specified in the variable. But the images in the email will look like this below screenshot.

email attachments

Although after downloading the images, the user will be able to view the actual image, it is not correct to show a blank thumbnail to the user in the email. Users will not be able to view the images directly in the email.

Therefore, to resolve this issue we will need to give all the information required to the Mailable object so that it could recognize the image or file and show the thumbnail accordingly.

Solution:

foreach($attachments as $attachment){
$message->attach($attachment->getRealPath(),[
		'as' => $attachment->getClientOriginalName(),
		'mime' => $attachment->getClientMimeType()						]);							
}

Here, in this above code, we are sending the original name as well as the mime type of the image to the Mailable object.
getClientOriginalName() is the method to get the original name of the file.
getClientMimeType() is the method to get the type of the file.

It will help the class object to recognize the type of file and also its name. Therefore, it will automatically attach the extension along with the original name of each image in the email and Mailable will show the thumbnail accordingly.
email attachments1

Leave a Reply

Your email address will not be published. Required fields are marked *