cuartas15
7 months ago
793
3
Laravel

How to change the email configuration for Laravel notifications on the fly?

Posted 7 months ago by cuartas15

I'm using Laravel email notifications to send my emails because that's enough for my needs.

Now, I need to use a new email configuration for a specific type of email I pretend to send, so the mailgun config I have on my .env file cannot be used, I've found guides but using mailable directly, I sill wanna keep using notifications for consistency.

This is basically the layout for each type of message I'm sending throughout my application:

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class SmeClientMailContact extends Notification
{
    use Queueable;

    /**
     * Create a notification instance.
     *
     * @param  string  $message
     * @param  string  $email
     * @param  string  $phone
     * @param  string  $contactName
     * @return void
     */
    public function __construct($message, $email, $phone, $contactName)
    {
        $this->message = $message;
        $this->email = $email;
        $this->phone = $phone;
        $this->contactName = $contactName;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->from(config('app.contact_email'), config('app.contact_email_name'))
            ->subject('Su Médico Especialista - Mensaje de contacto de ' . $this->contactName)
            ->greeting('Mensaje de contacto de ' . $this->contactName)
            ->line('Este cliente acaba de enviar un correo de contacto a sumedicoespecialista.')
            ->line('Nombre: ' . $this->contactName)
            ->line('Correo electrónico: ' . $this->email)
            ->line('Teléfono: ' . $this->phone)
            ->line('Mensaje: ' . $this->message);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

What's the way to manually set the mail driver, host, port, etc for this notification specifically for example.

Thanks in advance

Please sign in or create an account to participate in this conversation.