Mailgun - Inbound email attachment save to laravel

2019-08-22 17:38发布

问题:

When the request of an inbound email is parsed by the controller, the attachments are a json blob array of the form below.

"attachments": [
    {
        "url": "https://se.api.mailgun.net/v3/domains/mg.example.com/messages/eyJwIjpmYWxzZSwiayI6IjBhYjM5MWE5LTU5YzUtNGJkMS1hMzE5LTBhNjU0ODAwOTY4ZCIsInMiOiIyYWMyN2YxYzc2IiwiYyI6InRhbmtiIn0=/attachments/0",
        "content-type": "text/csv",
        "name": "widget-order.csv",
        "size": 554
    }
]

An inbound email has one or more attachments accessible through authentication. For this purpose, the method below makes use of GuzzleHttp\Client.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Collection;
use GuzzleHttp\Client;

class MailgunWidgetsController extends Controller
{
    public function store(Request $request)
    {
        try
        {
            $attachs = request('attachments');

            if(!is_null($attachs)) {
                $attachments = json_decode($attachs, true);

                foreach($attachments as $k => $a) {
                    $httpClient = new Client();
                    $resp = $httpClient->request('GET', $a['url'], ['auth' => ['api' => 'key-example']]);
                    $imageData = $resp->getBody();
                    $base64 = base64_encode($imageData);
                    $this->saveTicketAttachment($base64, $a['name'], $ticket);
                }
            }
            return response()->json(['status' => 'ok']);
        }   
        catch(\Exception $e) 
        {
            return response()->json(['status' => 'ok']);
        }
    }
}

Now, the code block enters the foreach, the url of the attachment is given by $a['url'] but the GET request fails. I think an exception of some kind has occurred but it does not get logged in the laravel.log file because the code execution stops at the GET request.

Objective is to access this attachment and convert it to its base64 encode.

回答1:

The correct implementation to generate a base64 encoded string from an inbound email attachment using GuzzleHttp\Client as:

private function getTicketAttachment($attachment)
{
    $httpClient = new Client();
    $response = $httpClient->get($attachment['url'], [
        'auth' => ['api', env("MAILGUN_SECRET")], 
    ]);
    $imageData = (string)$response->getBody();
    $base64 = base64_encode($imageData);
    return $base64;
}


回答2:

I write this for others coming here following the tutorial on laravel news

this is how you grab the file and puts it in your storage folder:

Storage::put(.$file['name'], $response->getBody());