<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Shahrukh A. Khan</title>
    <description>The latest articles on Forem by Shahrukh A. Khan (@shaz3e).</description>
    <link>https://forem.com/shaz3e</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1057409%2F030984b8-75ce-4fe8-87cb-39b26fc2c468.jpeg</url>
      <title>Forem: Shahrukh A. Khan</title>
      <link>https://forem.com/shaz3e</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/shaz3e"/>
    <language>en</language>
    <item>
      <title>Step-by-Step Guide to Sending Emails in Laravel Using Multiple SMTP Servers</title>
      <dc:creator>Shahrukh A. Khan</dc:creator>
      <pubDate>Wed, 07 Aug 2024 14:58:39 +0000</pubDate>
      <link>https://forem.com/shaz3e/step-by-step-guide-to-sending-emails-in-laravel-using-multiple-smtp-servers-1ie5</link>
      <guid>https://forem.com/shaz3e/step-by-step-guide-to-sending-emails-in-laravel-using-multiple-smtp-servers-1ie5</guid>
      <description>&lt;p&gt;Sending emails is a crucial feature in many web applications, from user notifications to marketing campaigns. In Laravel, a popular PHP framework, configuring email delivery is straightforward. However, ensuring reliable email delivery often requires the use of multiple SMTP servers. By setting up multiple SMTP servers, you can create a fallback mechanism that enhances the reliability and efficiency of your email delivery system.&lt;/p&gt;

&lt;p&gt;In this article, we will explore the process of configuring Laravel to send emails using multiple SMTP servers. Whether you're dealing with high-volume email campaigns or ensuring redundancy for mission-critical notifications, mastering this setup will help you maintain seamless communication with your users. We'll walk you through the necessary steps, offering tips and best practices along the way. Let's dive in and make your Laravel email system robust and dependable!&lt;/p&gt;

&lt;p&gt;First we need to create config option inside config/mail.php inside mailer array there is a default smtp array like below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        'smtp' =&amp;gt; [
            'transport' =&amp;gt; 'smtp',
            'url' =&amp;gt; env('MAIL_URL'),
            'host' =&amp;gt; env('MAIL_HOST', '127.0.0.1'),
            'port' =&amp;gt; env('MAIL_PORT', 2525),
            'encryption' =&amp;gt; env('MAIL_ENCRYPTION', 'tls'),
            'username' =&amp;gt; env('MAIL_USERNAME'),
            'password' =&amp;gt; env('MAIL_PASSWORD'),
            'timeout' =&amp;gt; null,
            'local_domain' =&amp;gt; env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
        ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;so we can create similar array with only required field env variables and we wil name it as &lt;code&gt;backup_smtp&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        'backup_smtp' =&amp;gt; [
            'transport' =&amp;gt; 'smtp',
            'host' =&amp;gt; env('MAIL_BACKUP_HOST', '127.0.0.1'),
            'port' =&amp;gt; env('MAIL_BACKUP_PORT', 2525),
            'encryption' =&amp;gt; env('MAIL_BACKUP_ENCRYPTION', 'tls'),
            'username' =&amp;gt; env('MAIL_BACKUP_USERNAME'),
            'password' =&amp;gt; env('MAIL_BACKUP_PASSWORD'),
        ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Than we will update our .env files with real SMTP server settings like below&lt;/p&gt;

&lt;p&gt;Default SMTP Server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MAIL_HOST=mail.example.com
MAIL_PORT=587
MAIL_USERNAME=primary@example.com
MAIL_PASSWORD=YOUR_SUPER_SECURE_PASSWORD
MAIL_ENCRYPTION=tls
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Backup SMTP Server&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MAIL_BACKUP_HOST=mail.backup-server.com
MAIL_BACKUP_PORT=587
MAIL_BACKUP_USERNAME=backup@email.com
MAIL_BACKUP_PASSWORD=YOUR_SUPER_SECURE_PASSWORD
MAIL_BACKUP_ENCRYPTION=tls
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Until now we have created our Main SMTP Server and Backup STMP Server its time to configure our application to send email with the mail service for this we need to create an abstract class from the command line.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:class Services/MailService
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above command will create a MailService class inside app/Service/MailService.php&lt;/p&gt;

&lt;p&gt;The next step to create a public function with &lt;code&gt;sendMail()&lt;/code&gt; mail which will require 2 arguments the first argument will be mailable so we can use different mailable classes from laravel Mail and the second argument will be the recipient to whom we are sending email to.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MailService.php&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Services;

use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class MailService
{
    public function sendEmail($mailable, $recipient)
    {
        try {
            // Primary SMTP Server
            Mail::mailer('smtp')
                -&amp;gt;to($recipient)
                -&amp;gt;send($mailable);

            Log::info("Email sent with Primary SMTP Server.");
        } catch (Exception $e) {
            Log::error("Primary SMTP Server failed to send email" . $e-&amp;gt;getMessage());
            try {
                // Primary SMTP Server
                Mail::mailer('backup_smtp')
                    -&amp;gt;to($recipient)
                    -&amp;gt;send($mailable);

                Log::info("Email sent with Backup SMTP Server.");
            } catch (Exception $e) {
                Log::error("Backup SMTP Server failed to send email" . $e-&amp;gt;getMessage());
                Log::error("Both SMTP Server failed to send email" . $e-&amp;gt;getMessage());
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To connect this MailService class with our application we will create MailServiceProvider to make things easier and scalable so we will create provider via artisan command as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:provider MailServiceProvider
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which will be created inside &lt;code&gt;app/Providers/MailServiceProvider.php&lt;/code&gt; and we will register our MailService class within laravel container but we do not want this to boot every time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Providers;

use App\Services\MailService;
use Illuminate\Support\ServiceProvider;

class MailServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this-&amp;gt;app-&amp;gt;singleton(MailService::class, function($app){
            return new MailService();
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we'll create a mailable with markdown to send email for this we need to use an artisan command as below since this tutorial is dedicated to enhance the functionality for SMTP I will not be covering mailable here but to sake of this tutorial we will create mailable and controller to send email via artisan command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:mail SendEmail --markdown=emails.send-email
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above artisan command will create a mailable inside &lt;code&gt;app/Mail&lt;/code&gt; directory as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class SendEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this-&amp;gt;mailData = $mailData;
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Send Email',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown: 'emails.send-email',
            with: [
                'mailData' =&amp;gt; $this-&amp;gt;mailData
            ],
        );
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can send email in different ways within laravel i.e. Observer or Jobs but to keep things simple we will create controller via artisan command for this tutorial and we will use a &lt;code&gt;protected&lt;/code&gt; variable and construct function to load our MailService class when it is being called and I am assuming you are aware of how to create views and validate the post request in laravel.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:controller EmailController
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;

use App\Mail\SendEmail;
use App\Services\MailService;
use Exception;
use Illuminate\Http\Request;

class EmailController extends Controller
{
    protected $mailService;

    public function __construct(MailService $mailService)
    {
        $this-&amp;gt;mailService = $mailService;
    }

    public function myForm()
    {
        return view('my-form');
    }

    public function myFormPost(Request $request)
    {
        // validate the request

        $emailData = [
            'name' =&amp;gt; $request-&amp;gt;name,
            'email' =&amp;gt; $request-&amp;gt;email,
        ];

        $mailable = new SendEmail($emailData);

        try{
            $this-&amp;gt;mailService-&amp;gt;sendEmail($mailable, $emailData['email']);

            return response()-&amp;gt;json(['message' =&amp;gt; 'Email has been sent']);
        }catch(Exception $e){
            return response()-&amp;gt;json(['message' =&amp;gt; $e-&amp;gt;getMessage()]);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For this tutorial we have created a minimal form fields just name and email.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form action="{{ route('post.form') }}" method="POST"&amp;gt;
    @csrf
    &amp;lt;input type="text" name="name"&amp;gt;
    &amp;lt;input type="email" name="email"&amp;gt;

    &amp;lt;input type="submit" value="Send Email"&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now will create routes inside web.php to send emails in laravel using multiple SMTP Servers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('/send', [EmailController::class, 'myForm'])-&amp;gt;name('post.form');
Route::post('/send', [EmailController::class, 'myFormPost']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's time to go on the browser and send emails using our codes which we have done so far so open up your browser and test route /send in my case.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http://laravel.test/send
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If everything works you should be able to see in browser after filling out the form and click send button you should see as below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"message":"Email has been sent"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are logging messages inside laravel.log with &lt;code&gt;Log::info();&lt;/code&gt; and &lt;code&gt;Log::error();&lt;/code&gt; inside our MailService class we should also see the following message if the mail sent from Primary SMTP server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;local.INFO: Email sent with Primary SMTP Server.  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once everything works as expected we will change the password for our primary SMTP server email to check if the email is being sent from backup SMTP server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;local.ERROR: Primary SMTP Server failed to send email (along with actual message)
local.INFO: Email sent with Backup SMTP Server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can make sure if the email failed for any reason from primary SMTP server it will be send via backup SMTP server but if the backup SMTP server couldn't send email user/admin will not receive an email.&lt;/p&gt;

&lt;p&gt;We hope you enjoyed this guide and learned something new about sending emails in Laravel using multiple SMTP servers. If you found this article helpful, feel free to follow us on &lt;a href="https://x.com/DiligentCreator" rel="noopener noreferrer"&gt;X&lt;/a&gt;, &lt;a href="https://www.instagram.com/diligentcreators" rel="noopener noreferrer"&gt;Instagram&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This blog post was written by the awesome team at &lt;a href="https://diligentcreators.com" rel="noopener noreferrer"&gt;diligentcreators.com&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>laravel</category>
      <category>tutorial</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Save server resource in Laravel</title>
      <dc:creator>Shahrukh A. Khan</dc:creator>
      <pubDate>Tue, 16 Jul 2024 11:26:08 +0000</pubDate>
      <link>https://forem.com/shaz3e/save-server-resource-in-laravel-5b93</link>
      <guid>https://forem.com/shaz3e/save-server-resource-in-laravel-5b93</guid>
      <description>&lt;p&gt;How do you save server resource in Laravel 11?&lt;/p&gt;

&lt;p&gt;Go to routes/web.php&lt;/p&gt;

&lt;p&gt;and add middleware to your route or route group just remember the key which will be using throughout the application in this case I am using &lt;code&gt;weather&lt;/code&gt; as key to limit the request by User or IP. just remember whatever key you use should be same as the key in app/Providers/AppServiceProvider.php&lt;/p&gt;

&lt;p&gt;so my route/web.php should look like this when I use the middleware with the single route&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::get('/your-url', function () {
    return response()
        -&amp;gt;json([
            'data' =&amp;gt; 'data will be here'
        ]);
})-&amp;gt;middleware(['throttle:weather']);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or if you want to use route group&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Route::middleware(['throttle:weather'])-&amp;gt;group(function () {
    // User CRUD controller
    Route::resource('/users', UserController::class);

    // Change Password View
    Route::get('/profile/change-password', [UserController::class, 'changePassword'])-&amp;gt;name('change.password');

    // Change Password Store
    Route::post('/profile/change-password', [UserController::class, 'changePasswordStore'])-&amp;gt;name('change.password.store');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Than inside your app/Providers/AppServiceProvider.php within boot method you can limit the user or ip make sure to import the following namespaces&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('weather', function (Request $request) {
            return Limit::perMinute(10)
            -&amp;gt;by($request-&amp;gt;user()?-&amp;gt;id ?: $request-&amp;gt;ip()); // 10 request per minute per user or ip

        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;of if you want to limit normal user vs logged in user use the following.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('weather', function (Request $request) {
            // Rate Limit by Logged in User vs Normal User
            return $request-&amp;gt;user() ?
                Limit::perMinute(2)-&amp;gt;by($request-&amp;gt;ip()) :
                Limit::perMinute(1)-&amp;gt;by($request-&amp;gt;ip());
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By following this you can now save your server resource and keep user informed they are only allowed certain request per minute this could for per seconds and hours following are some useful methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// perSecond takes 1 argument
Limit::perSecond($maxAttempts: 1)-&amp;gt;by($key: $request-&amp;gt;ip())

// perMinute takes 1 argument
Limit::perMinute($maxAttempts: 1)-&amp;gt;by($key: $request-&amp;gt;ip())

// perMinutes takes 2 argument
Limit::perMinutes($decayMinutes: 1, $maxAttempts: 10)-&amp;gt;by($key: $request-&amp;gt;ip())

// perHour takes 2 argument
Limit::perHour($maxAttempts: 100, $decayHours: 1)-&amp;gt;by($key: $request-&amp;gt;ip())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;when you want to use limit you can save server resource when you have hosted your application where your server provider charges for the resource.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>I need your help</title>
      <dc:creator>Shahrukh A. Khan</dc:creator>
      <pubDate>Sun, 02 Apr 2023 16:58:08 +0000</pubDate>
      <link>https://forem.com/shaz3e/i-need-your-help-3k09</link>
      <guid>https://forem.com/shaz3e/i-need-your-help-3k09</guid>
      <description>&lt;p&gt;&lt;a href="https://stackoverflow.com/questions/75913189/how-to-create-payment-intent-with-php-using-stripe-element" rel="noopener noreferrer"&gt;Need Help at StackOverFlow&lt;/a&gt;&lt;/p&gt;

</description>
      <category>help</category>
    </item>
  </channel>
</rss>
