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
You can pass custom sender parameters when dispatching your
TicketIssueEmail
, something like this:Then, inside the
TicketIssueEmail
, add load that parameter in constructor:Then, in the
envelope()
method, you can send a custom sender email:Read more on official documentation
Modify your TicketIssueEmail class: Add a constructor parameter for the from address (email and name) and use the from method to set it dynamically.
Update your controller. Ensure that you use use
IlluminateSupportFacadesAuth;
??