Laravel: Use Email and Name in Mail::to - php

I have a contact form where someone provides his name and email. I want to send him an email now with Laravel.
I found in the docs
To send a message, use the to method on the Mail facade. The to method
accepts an email address, a user instance, or a collection of users.
and in fact
\Mail::to('example#gmail.com')->send(new \App\Mail\Hello);
works. But is it also possible to provide the name for the email receipt?
I wanted to look that up in the Laravel API for the Mail Facade but to my surprise the facade has no to function?
So how can I find out what the to function really does and if I can pass a name parameter as well?

In laravel 5.6, answer to your question is: use associative array for every recpient with 'email' and 'name' keys, should work with $to, $cc, $bcc
$to = [
[
'email' => $email,
'name' => $name,
]
];
\Mail::to($to)->send(new \App\Mail\Hello);

You can use the Mail::send() function that inject a Message class in the callable. The Message class has a function to($email, $name) with the signature you're searching, i.e.:
Mail::send($view, $data, function($message) use ($email, $name) {
$m->to($email, $name);
$m->from('youremail#example.com', 'Your Name');
$m->subject('Hi there');
})
The $view could be a string (an actual view) or an array like these:
['text'=> 'body here']
['html'=> 'body here']
['raw'=> 'body here']
The $data argument will be passed to the $view.

For Laravel < 5.6 one can use this:
$object = new \stdClass();
$object->email = $email;
$object->name = $user->getName();
\Mail::to($object)->queue($mailclass);
see here

I prefer this solution as more readable (no need to use arrays and static string keys).
\Mail::send((new \App\Mail\Hello)
->to('example#gmail.com', 'John Doe');

You can use Mailable class in Laravel:
https://laravel.com/docs/5.5/mail
php artisan make:mail YouMail
These classes are stored in the app/Mail directory.
In config/mail.php you can configue email settings:
'from' => ['address' => 'example#example.com', 'name' => 'App Name'],

for Laravel 8 is like this:
$user = new User;
$user->email = 'example#example.com';
Mail::to($user)->send(new YourMail);
YourMail is Mailable class created by php artisan make:mail YourMail

Related

How to pass variables from Job Queue class to Mail view template

I am trying to pass variables from Job Queue class to Mail view template like the following example.
$snippet = Constant_model::getDataOneColumn("snippets","id",$this->details['snippet_id']);
$snippet_details = [
'snippet_name'=> $snippet[0]->snippets_name,
'snippet_image'=> $snippet[0]->snippet_image,
'snippet_url'=> $snippet[0]->url_slug
];
$subscribers = Constant_model::getDataOneColumn("user_followers","receiver_id",$this->details['published_by']);
foreach($subscribers as $subscriber){
$user =User::find($subscriber->sender_id);
Mail::to($user->email)->send(new Notifynewsnippet($snippet_details));
}
Mail template
{{$snippet_details['snippet_name']}}
But I am getting the error. please help
You can pass on variablea via view. It is available in the class Mailable:
$this->view('mails.hello', ['name' => $name])

Laravel 5.4 change the subject of markdown mail

I have used markdown mailables which is a new feature in laravel 5.4. I have successfully implemented a mail sender. It seems, the subject of the mail is named as the name of the mailable class. I need to change the subject of the mail and it's hard to find any resources regarding this.
There is subject method in laravel mailables.
All of a mailable class' configuration is done in the build method. Within this method, you may call various methods such as from, subject, view, and attach to configure the email's presentation and delivery. : https://laravel.com/docs/5.4/mail#writing-mailables
You can achieve this like this :
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->subject('Your Subject')
->markdown('emails.orders.shipped');
}
You may need to execute php artisan view:clear after modifying your class.
If the email subject is the same for all emails then just overload the $subject parameter in your extended Mailable class.
/**
* The subject of the message.
*
* #var string
*/
public $subject;
complete code (tested)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
class ContactController extends Controller {
public function sendContactMail(Request $request) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'user_message' => 'required'
]);
Mail::send('contact_email',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'subject' => $request->get('subject'),
'user_message' => $request->get('user_message'),
), function($message) use ($request)
{
$message->from($request->email );
$message->subject("Your Subject");
$message->to('email to');
});
return back()->with('success', 'Your message was sent successfully');
}
}

Unit Testing Mail Queue on Laravel 5

I'm facing two situations that I would like to address / understand.
1st - How do I Unit Test Laravel's Mail Queue Class?
The code that I want to test is this:
// Create new customer record
$account = $this->create(['account_id' => $account->id]);
// Get email address to send welcome email.
$email = $data['email'];
// Email Subject
$subject = $this->word('emails.welcome.subject');
$this->mailQueue->queue('emails.welcome',
['some_data' => 'data'],
function ($message) use ($email, $subject) {
$message->to($email)->subject($subject);
}, true);
return $account;
I would like to know where is the shouldReceive method that will work for me when using Illuminate\Contracts\Mail\MailQueue class.
Right now I have this unit test for this:
/**
* #tests
*/
public function it_should_sign_up_a_new_user() {
// MailQueue::shouldReceive() does not exist.
list($account, $email) = $this->getAccountData();
$request = array_merge($account, $email);
$account['password'] = $this->hash($account['password']);
$this->post('/signup', $request, $this->header)
->assertResponseOk()
->seeInDatabase('account', $account)
->seeInDatabase('email', $email);
}
2nd - Why Unit Test does not require php artisan queue:listen or queue:work?
Every time I run the Unit Test, the email gets dispatched even though I have no queue:listen running. I would like to understand how this awesome magic happens.
Per the docs it looks like they recommend using Mail::queue . i.e.
Mail::queue('emails.welcome', $data, function($message)
{
$message->to('foo#example.com', 'John Smith')->subject('Welcome!');
});
The Mail Facade has shouldReceive built into it so you should be able to do:
Mail::shouldReceive('queue')->once()
https://laravel.com/docs/5.0/mail#queueing-mail

PHP Laravel 5 User class properties not accessible for sending Email after account creation

I have a problem where I can't put in the variables into the Mail::send() function in laravel. Please see the following code:
$first_name = $request->input('first_name'),
$email = $request->input('email'),
//Create account
User::create([
'first_name' => $first_name,
'last_name' => $request->input('last_name'),
'email' => $email,
'password' => bcrypt($request->input('password')),
]);
//Send email to user
Mail::send('emails.test', ['fname' => $first_name], function($message)
{
$message->to($email)
->subject('Welcome!');
});
return redirect()
->route('home')
->with('info', 'Your account has been created and an authentication link has been sent to the email address that you provided. Please go to your email inbox and click on the link in order to complete the registration.');
For some reason the code breaks when it gets to the send email because I receive the error and the data is sent to the database. Why is the variable no longer accessible afterwards?
Any help would be greatly appreciated. Thank you
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Source: http://php.net/manual/en/functions.anonymous.php
In other words, $email has to be inherited like this:
Mail::send('emails.test', ['fname' => $first_name], function($message) use ($email)
{
$message->to($email)
->subject('Welcome!');
});
Note: use ($email) in the first line.

Laravel problems when sending email

When I'm trying to send an email using the swiftmailer in laravel I get the folowing error: "Missing argument 2 for UsersController::{closure}()".
My code is below:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message, $mail, $subject = 'Welcome!')
{
$message->to($mail)->subject($subject);
});
It's really weird though. The $mail variable contains a valid email address and I'm not using the UsersController at all in this script.
Thanks in advance
You must pass only the $message to the closure. Any additional variable must be passed down with the use keyword:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message) use($mail, $subject)
{
$subject = empty($subject) ? 'Welcome!' : $subject;
$message->to($mail)->subject($subject);
});

Categories