Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending mail in Laravel 5.4 using Mailgun get error code " 401 UNAUTHORIZED` response: Forbidden "

I'm trying to send mail in Laravel 5.4 project with Mailgun. I think I set the configuration correctly. But, I got this error message such as

ClientException in RequestException.php line 111: Client error: POST https://api.mailgun.net/v3/sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org/messages.mime >resulted in a 401 UNAUTHORIZED response: Forbidden

Here is my configuration:

in .env file

MAIL_DRIVER=mailgun
MAILGUN_DOMAIN=sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org
MAILGUN_SECRET=pubkey-1767e**********

in mail.php file

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
    'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
    'name' => env('MAIL_FROM_NAME', 'Richi Htoo'),
],

in services.php file

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

and I wrote mail sending code in default route such as

Route::get('/', function () {
//return view('welcome');

    $data = [
        'title' => 'Hi student I hope you like the course',
        'content' => 'This laravel course was created with a lot of love and dedication for you'
    ];

    Mail::send('emails.test', $data, function($message){
        $message->to('[email protected]', 'White Nuzzle')->subject('Hello student how are you?');
    });
});

And I also installed Laravel Package "guzzlehttp/guzzle" version 6.2 to send mail.

But when I call that default home route, I got an error message as I mention above.

I can't find any solution for my error in any where including this forum "stackoverflow.com".

Can anyone help me please?

like image 768
White Nuzzle Avatar asked Apr 14 '17 16:04

White Nuzzle


2 Answers

Ok found it, In the file "vendor\laravel\framework\src\Illuminate\Mail\Transport\MailgunTransport.php", the endpoint used is US one.

As said in documentation, https://documentation.mailgun.com/en/latest/api-intro.html#mailgun-regions, you have an endpoint for US and EU.

If you are european, you must use "api.eu.mailgun.net" or you get a 401.

Just change the endpoint: Laravel is powerful and they think about that. You can add an 'endpoint' key to the config/services.php/mailgun entry.

like image 160
user2408789 Avatar answered Sep 19 '22 20:09

user2408789


If you are not using the United States Mailgun region, you can define your region's endpoint in the services configuration file:

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
    'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'),
],

Alternatively, one can define the MAILGUN_ENDPOINT in the .env file:

MAILGUN_ENDPOINT="api.eu.mailgun.net"
like image 35
Darren Murphy Avatar answered Sep 17 '22 20:09

Darren Murphy