Mailgun is a very popular API that allows you to send emails directly from the website. We used it in a product lottery, which we have been preparing recently for one of our foreign clients. One of its key advantages is the ability to track e-mails, we can thus collect much more accurate data on user behavior. Sending messages by this method in comparison with, for example, popular SMTP mailing significantly reduces the chance that the message will fall into SPAM or be rejected by the client’s server.
In this post I am going to introduce you how you can easily configure Laravela to work with Mailgun.
First, we need to enter new data into our .env configuration file.
1 2 3 4 5 6 7 8 | MAIL_DRIVER=mailgun MAIL_HOST=smtp.mailgun.org MAIL_PORT=2525 MAIL_USERNAME=twojAdresEmail@esumomedia.com MAIL_PASSWORD=twojeHaslo MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=nadawca@esumomedia.com MAIL_FROM_NAME='Nazwa nadawcy' |
If you have not created your account on MailGun.com so far, this is the last moment to do it. The second step is adding the domain and secret key available in our MailGun administration panel.
1 2 3 4 | 'mailgun' => [ 'domain' => 'esumomedia.com', 'secret' => 'key-W7S4nynT76cXgmMsmCgB70OBBSbOsTwO', ], |
Once you have all the information you need, go to the file /config/services.php and add the above data in the following way:
1 | Route::post('/testemail', 'HomeController@testEmail'); |
We now need a function connected to the path testemail in order to do this, enter the /app/Http/Controllers/HomeController.php file and create the testEmail function.
1 2 3 4 5 6 7 | public function testEmail(){ $email ='youremail@yourdomain.com'; \Mail::raw('Description of test email',function ($message) use ($email) { $message->to($email); $message->subject('This is test email'); }); } |
Everything is ready to check if you have been able to go through the browser on the link /testemail, check if the email reached the target mailbox and enjoy the properly configured API!