0
votes

I have the code below to send emails using the Mail::to function. But Im not understanding how to set the subject and body of the message with the Mail::to function. I have the code below that is working to send emails but without subject and the $message is also not appearing in the email.

Do you know how to properly achieve that? (Have subject and the $request->message in the email using Mail::to)

public function send(Request $request, $id){

    $conference = Conference::find($id);

    if($request->send_to == "participant"){
      // if is to send only 1 email the Mail::to is called directly here 
        Mail::to($request->participant_email)->send(new Notification($conference));
        return;
    }
    if($request->send_to == "all"){
        // $sendTo = query to get a set of emails to send the email
    }
    else{
        // $sendTo = query to get a another set of emails to send the email
    }

    foreach($sendTo as $user){
        $usersEmail[] = $user->email;
    }

    $message = $request->message;
    $subject = $request->subject;

    foreach ($usersEmail as $userEmail){
        Mail::to($userEmail)->send(new Notification($conference, $message));
    }
}

In the class Notification I have:

class Notification extends Mailable
{
    public $conference;

    public function __construct(Conference $conference)
    {
        $this->conference = $conference;
    }

    public function build()
    {
        return $this->markdown('emails.notification');
    }
}

In the view notifications.blade.php I have:

@component('mail::message')
# Notification relative to {{$conference->name}}

{{$message}}

Thanks,<br>
{{ config('app.name') }}
@endcomponent
3

3 Answers

0
votes

Try something like this:

$emailData = array(
/* Email data */
'email'     => '[email protected]',
'name'      => 'User name',
'subject'   => 'Email subject',
);

Mail::send('emails.template_name', ['emailData' => $emailData], function ($m) use ($emailData) {    // here it is a closure function, in which $emailData data is available in $m
$m->from('[email protected]', 'Domain Name');

$m->to($emailData['email'], $emailData['name'])->subject($emailData['subject']);
});
0
votes
try 
{ 
    Mail::send('emails.contact_form', ['data' => $data], 
    function($message) use ($data)
    {
        $message->from('[email protected]', 'ShortName');
        $message->to( $data['adminEmail'] )->subject("Contact Form" );
    }); 
    return true;
}
catch (\Exception $ex) {
    $ex->getMessage();
    return false;            
}
0
votes

As you already have one template in your code use that template, Pass the message to template

$subject = 'Email Subject';
Mail::send('emails.notification', ['message' => $message], function ($mail) use ($userEmail, $subject) {
    $mail->from('[email protected]', 'Domain Name');
    $mail->to($userEmail)->subject($subject);
});