email function not passing variable to view - php

i want to pass a variable $data to my email views but i get undefined variable.
this is the controller method
public function broadcastemail(Request $request)
{
$this->validate($request,
[
'subject' => 'required',
'emailMessage' => 'required'
]);
$emailMessage = $request->emailMessage;
$data['emailMessage'] = $emailMessage;
Mail::send('backend.user.emailMessage', $data, function($message)
{
$subject = request()->subject;
$user = User::find('31');
$email = $user->email;
$name = $user->first_name;
$message->to($email, $name)->subject($subject)->with('data',$data);
});
//Mail::to($to)->send($data);
//send_email($to, $name, $subject, $message);
return back()->withSuccess('Mail Sent Successfuly');
}
and this is my view
<p>{{$data['emailMessage']}}</p>

try to use {{ $emailMessage }} instead of {{$data['emailMessage']}} in your view and use keyword for using inside the closure function of MAIL

Related

Error in send email (Mail) later laravel 5?

I use the instructions https://laravel.com/docs/5.8/mail
to send an email later than expected, but I get an error when I try to send it:
ErrorException (E_ERROR)
Only mailables may be queued. (View: ....
Please for help.
My methods to send:
public static function sent_info_email_later ($data_f, $minuts) {
$data = json_decode($data_f);
$when = now()->addMinutes($minuts);
return Mail::later($when,'emails.message', ['title' => $data->subject, 'body' => $data->body], function ($message) use ($data, $when)
{
$message->from(env('MAIL_USERNAME'), 'NETPlatform24');
if(gettype($data->to) == 'array') {
$dest_to = $data->to;
} else {
$dest_to = explode(', ', $data->to)[0];
}
$message->to($dest_to);
$message->subject($data->subject);
return true;
});
}
and calling index.php
$data = json_encode(array('to' => 'my email', 'subject' => 'This email was send 1 min after run', 'body' => 'time now'.now().'<br> time send: '.now()->addMinutes(1)));
$send_mail = \App\Http\Controllers\Backend\Auth\Mail\MailController::sent_info_email_later($data, 1);
I wrote this code long time ago. I hope this will help to clarify. For each Cargo I send a email using queue.
<?php
public function mails_meeting($meeting, $group, $place, $date, $message, $user)
{
$subject = "meeting " . $group;
$cargos = Cargo::where('comision_id', '=', $meeting->comision_id)->where('active', '=', '1')->get();
foreach ($cargos as $cargo) {
$mail_reciever = $cargo->asambleista->user->email;
Mail::queue('correos.comision_mail', ['group' => $group, 'place' => $place,
'date' => $date, 'message' => $message, 'user' => $user],
function ($mail) use ($subject, $mail_reciever) {
$mail->from('siarcaf#gmail.com', 'Automatic mail system');
$mail->to($mail_reciever);
$mail->subject($subject);
});
}
return 0;
}
In your_app/config/mail.php .
'sendmail' => '/usr/sbin/sendmail -bs',
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
.env file
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=your_conf
The error you're getting (and the docs) indicate that the second argument passed to the later method must be an instance of Illuminate\Mail\Mailable.
Where you currently have the string 'emails.message', you will need to replace this with an instance of Mailable that represents the email message that you're trying to send.
For example, create this file in /app/Mail (create the folder if it doesn't exist):
<?php
namespace App\Mail;
use Illuminate\Mail\Mailable;
use Illuminate\Contracts\Queue\ShouldQueue;
class InfoEmail extends Mailable implements ShouldQueue
{
public $subject;
public $body;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($subject, $body)
{
$this->subject = $subject;
$this->body = $body;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from(env('MAIL_USERNAME'), 'NETPlatform24')
->subject($this->subject)
->view('emails.message', ['title' => $this->subject, 'body' => $this->body]);
}
}
This assumes that 'emails.message' is the view file you intend to use for this email, located at /resources/views/emails/message.blade.php relative to your project's root. I'd actually recommend changing this to something a bit more descriptive.
You'll then need to change your sent_info_email_later method to something like this:
public static function sent_info_email_later ($data_f, $minuts) {
$data = json_decode($data_f);
$when = now()->addMinutes($minuts);
$recipients = is_array($data->to) ? $data->to : explode(', ', $data->to);
$recipients = array_filter(array_map('trim', $recipients));
$first_recipient = array_shift($recipients);
return Mail::to($first_recipient)
->cc($recipients)
->later($when, new InfoEmail($data->subject, $data->body));
}
I've taken the liberty of tidying up your recipients by extracting out the first recipient for the to and moving the rest to cc as this may play better with more email service providers.
Hope this helps!

Show the subject and message sending email with Mail::to

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
Try something like this:
$emailData = array(
/* Email data */
'email' => 'user#email.com',
'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('info#domain.com', 'Domain Name');
$m->to($emailData['email'], $emailData['name'])->subject($emailData['subject']);
});
try
{
Mail::send('emails.contact_form', ['data' => $data],
function($message) use ($data)
{
$message->from('emailasinenv#hosting.com', 'ShortName');
$message->to( $data['adminEmail'] )->subject("Contact Form" );
});
return true;
}
catch (\Exception $ex) {
$ex->getMessage();
return false;
}
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('info#domain.com', 'Domain Name');
$mail->to($userEmail)->subject($subject);
});

Why am I getting undefined variable errors in Laravel method?

I have created a Laravel method in my PageController to send emails when form data is sent like the following:
public function sendMessage(Request $request)
{
$name = $request->input('name');
$email = $request->input('email');
$message_content = $request->input('message');
// email message
Mail::raw($message_content, function ($message)
{
$message->from($email, $name);
// $message->to(env('APP_ADMIN_EMAIL'));
$message->to("myemail#mail.com");
$message->subject('Website Message');
});
return "message sent";
}
But I get this error when the method is called:
ErrorException Undefined variable: email
Can someone explain what I'm doing wrong?
You need to pass the variables to the closure:
Mail::raw($message_content, function ($message) use ($email, $name)
{
$message->from($email, $name);
$message->to("myemail#mail.com");
$message->subject('Website Message');
});
See docs: https://secure.php.net/manual/en/functions.anonymous.php

How to send two different emails on one button click using Laravel

I am trying to send two emails at the same time when the user submits contact form. One email to the website owner and other to the user as autoresponse. I have been trying to do this for about last 4 hours and tried different solutions on internet but I am totally lost. Here is my code to send an email
public function contactForm(Request $request)
{
$parameters = Input::get();
$email = Input::get('email');
$inquiryType = Input::get('type_inquiry');
foreach ([
'contactmessage' => 'Message',
'email' => 'Email',
'phone' => 'Phone',
'first_name' => 'Contact Name',
'g-recaptcha-response' => 'Captcha',
] as $key => $label) {
if (!isset($parameters[$key]) || empty($parameters[$key])) {
return response()->json(
[
'success' => false,
'error' => "{$label} cannot be empty",
]
);
}
}
$recipients = 'abc#gmail.com';
// if page set, try to get recipients from the page settings
if (Input::get('page_id')) {
$page = Page::find(Input::get('page_id'));
if ($page && !empty($page->recipients)) {
$recipients = explode(',', $page->recipients);
}
}
try {
$res = Mail::send(
'emails.contact',
$parameters,
function (Message $message) use ($recipients) {
$message->subject('Contact message');
if (is_array($recipients)) {
// email to first address
$message->to(array_shift($recipients));
// cc others
$message->cc($recipients);
} else {
$message->to($recipients);
}
}
);
} catch (\Exception $e) {
return response()->json(
[
'success' => false,
'error' => $e->getMessage(),
]
);
}
if($inquiryType == 'Rental Inquiry'){
Mail::send(
'emails.autoresponse',
'',
function (Message $message) use ($email) {
$message->subject('Thank you for inquiring');
if (is_array($email) {
// email to first address
$message->to(array_shift($email);
// cc others
$message->cc($email);
} else {
$message->to($email);
}
}
);
}
return response()->json(
[
'success' => $res,
]
);
}
I have tried to do the same thing by different methods but none of them are working. Please help me. This is the first time I am sending multiple emails using laravel. I think I am doing a big and silly mistake somewhere.
Thank you.
You have a missing closing parenthesis near is_array($email)
$message->subject('Thank you for inquiring');
if (is_array($email)) {
Also i would you use laravel's validator to check for required input. Another suggestion would be to use queues for mails. Sending two mails in a single request might cause your page load time to increase significantly.
The best way is create one Laravel Jobs
php artisan queue:table
php artisan migrate
php artisan make:job SendEmail
Edit your .env
QUEUE_DRIVER=database
Edit your app /Jobs/SendEmail.php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Mail\Mailer;
class SendEmail extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $subject;
protected $view;
protected $data;
protected $email;
/**
* SendEmail constructor.
* #param $subject
* #param $data
* #param $view
* #param $email
*/
public function __construct($subject, $data, $view, $email)
{
$this->subject = $subject;
$this->data = $data;
$this->email = $email;
$this->view = $view;
}
/**
* Execute the job.
* #param $mailer
* #return void
*/
public function handle(Mailer $mailer)
{
$email = $this->email;
$subject = $this->subject;
$view = $this->view;
$mailer->send($view, $this->data,
function ($message) use ($email, $subject) {
$message->to($email)
->subject($subject);
}
);
}
}
And handle in your controller
use App\Jobs\SendEmail;
public function contactForm(Request $request) {
//TODO Configure Subject
$subjectOwner = 'Your Email Subject For Owner';
$subjectUser = 'Your Email Subject For User';
//TODO Configure Email
$ownerEmail = 'ownerEmail#gmail.com';
$userEmail = 'userEmail#gmail.com';
//TODO Configure Data Email send to email blade viewer
$dataEmail = [
'lang' => 'en',
'user_name' => 'User Name'
];
//emails.owner mean emails/owner.blade.php
//emails.admin mean emails/admin.blade.php
$jobOwner = (new SendEmail($subjectOwner, $dataEmail, "emails.owner" , $ownerEmail))->onQueue('emails');
dispatch($jobOwner);
$jobUser = (new SendEmail($subjectUser, $dataEmail, "emails.admin" , $userEmail))->onQueue('emails');
dispatch($jobUser);
}
And try command
//IF You using Laravel 5.2
php artisan queue:listen --queue=emails
//IF You using Laravel >5.3
php artisan queue:work

How to input external variable as in laravel mailer in users controller?

I have a function in user controller in laravel that allows users to enter their name and email in a form and send an email to administrator. But when I try to the variable containing them in the MailTo function, it gives error. Here is my code:
public function send_email_contact_us(){
$name = Input::get('name');
$email = Input::get('email');
$message_contact = Input::get('message');
$sender_email = Input::get('email');
$sender_name = Input::get('name');
$validator = Validator::make(
array(
'name' => $name,
'email' => $email
), array(
'name' => 'required',
'email' => 'required',
)
);
if ($validator->fails())
{
$error_messages = $validator->messages()->all();
return Redirect::back()->with('flash_errors',"Message not sent, please try again.");
}
else
{
$data=array("name"=>$name,"email"=>$email,"message_contact"=>$message_contact);
Mail::send('emails.contactus',$data, function($message)
{
$message->from($sender_email, $sender_name); // THIS GIVES ERROR
$message->to("admin#admin.com")->subject('Contact Us');
});
return Redirect::back()->with('flash_success',"Message sent successfully.");
}
}
Any help would be highly appreciated.
change to this
Mail::send('emails.contactus',$data, function($message) use($sender_email,$sender_name)
{
$message->from($sender_email, $sender_name);
$message->to("admin#admin.com")->subject('Contact Us');
});
To use external variables in a closure you have to import the variable into the closure by using the use keyword

Categories