skip to Main Content

I want to send email through smtp.gmail.com connection but with a sender declared in dynamic way.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=""
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME="${APP_NAME}"

In above code I declared username, mail-from-address, password But I want to set sender in my controller dynamically to be more specific with Auth::user()->email . How to do that?

<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesEnvelope;
use IlluminateQueueSerializesModels;

class TicketIssueEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $msg;
    public  $sub;
    /**
     * Create a new message instance.
     */
    public function __construct($msg, $subject)
    {
        //
        $this->msg= $msg;
        $this->sub= $subject;
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject:  $this->sub,
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'backend.customer.pages.email',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, IlluminateMailMailablesAttachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

This is my controller

 use AppMailTicketIssueEmail;
    use IlluminateSupportFacadesMail;
    public function ticket_add(Request $request)
    {
        $data = [];
        $admin = DB::table('users')->where('user_type','admin')>first();
        if ($request->isMethod('post')) {
            //dd($request->all());
       
            try {
               $ticket= Ticket::create([
                    'name' => $request->name,
                    'issue_date' =>date('Y-m-d', strtotime($request->issue_date)),
                    'description' => $request->description,
                    'created_by' => Auth::user()->id,
                   
                ]);
                $from=Auth::user()->email;
                $sender_name= Auth::user()->name;
                $to=$admin->email;
                $msg= $ticket->description;
                $subject= "New Ticket Named ". $ticket->name. " From ".  Auth::user()->name;
                Mail::to($to)->send(new  TicketIssueEmail($msg, $subject));
    
                return back()->with('success', 'Added Successfully');
            } catch (PDOException $e) {
                return back()->with('error', 'Failed Please Try Again'. $e);
            }
        }

Please help me out.

2

Answers


  1. You can pass custom sender parameters when dispatching your TicketIssueEmail, something like this:

    $senderEmail=Auth::user()->email;
    $senderName= Auth::user()->name;
    $to=$admin->email;
    $msg= $ticket->description;
    $subject= "New Ticket Named ". $ticket->name. " From ".  Auth::user()->name;
    Mail::to($to)->send(new  TicketIssueEmail($msg, $subject, $senderEmail, $senderName));
    

    Then, inside the TicketIssueEmail, add load that parameter in constructor:

    public $msg;
    public $sub;
    public $senderEmail;
    public $senderName;
    
    /**
     * Create a new message instance.
     */
    public function __construct($msg, $subject, $senderEmail, $senderName)
    {
        $this->msg = $msg;
        $this->sub = $subject;
        $this->senderEmail = $senderEmail;
        $this->senderName = $senderName;
    }
    

    Then, in the envelope() method, you can send a custom sender email:

    return new Envelope(
        subject: $this->sub,
        from: new Address($this->senderEmail, $this->senderName),
    );
    

    Read more on official documentation

    Login or Signup to reply.
  2. Modify your TicketIssueEmail class: Add a constructor parameter for the from address (email and name) and use the from method to set it dynamically.

    <?php
    
    namespace AppMail;
    
    use IlluminateBusQueueable;
    use IlluminateContractsQueueShouldQueue;
    use IlluminateMailMailable;
    use IlluminateMailMailablesContent;
    use IlluminateMailMailablesEnvelope;
    use IlluminateQueueSerializesModels;
    
    class TicketIssueEmail extends Mailable
    {
        use Queueable, SerializesModels;
        
        public $msg;
        public $sub;
        public $fromEmail;
        public $fromName;
        
       
        public function __construct($msg, $subject, $fromEmail, $fromName)
        {
            $this->msg = $msg;
            $this->sub = $subject;
            $this->fromEmail = $fromEmail;
            $this->fromName = $fromName;
        }
    
        
        public function envelope(): Envelope
        {
            return new Envelope(
                subject:  $this->sub,
                from: [$this->fromEmail => $this->fromName] // Set dynamic from email and name
            );
        }
    
        
        public function content(): Content
        {
            return new Content(
                view: 'backend.customer.pages.email',
            );
        }
    
       
        public function attachments(): array
        {
            return [];
        }
    }
    

    Update your controller. Ensure that you use use IlluminateSupportFacadesAuth; ??

    use AppMailTicketIssueEmail;
    use IlluminateSupportFacadesMail;
    use IlluminateSupportFacadesAuth;
    
    public function ticket_add(Request $request)
    {
        $admin = DB::table('users')->where('user_type','admin')->first();
    
        if ($request->isMethod('post')) {
            try {
                $ticket = Ticket::create([
                    'name' => $request->name,
                    'issue_date' => date('Y-m-d', strtotime($request->issue_date)),
                    'description' => $request->description,
                    'created_by' => Auth::user()->id,
                ]);
    
                $fromEmail = Auth::user()->email;
                $fromName = Auth::user()->name;
                $to = $admin->email;
                $msg = $ticket->description;
                $subject = "New Ticket Named " . $ticket->name . " From " . Auth::user()->name;
    
                // Pass the fromEmail and fromName dynamically
                Mail::to($to)->send(new TicketIssueEmail($msg, $subject, $fromEmail, $fromName));
    
                return back()->with('success', 'Added Successfully');
            } catch (PDOException $e) {
                return back()->with('error', 'Failed, Please Try Again: ' . $e->getMessage());
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search