I've been having this issue where I want to send a plaintext email to a user (me in this case) but the email adress is inside of an object I retrieved from the database. All examples using Mail::raw use a string but not a passed variable. Is there a way to do that?
Code:
Mail::raw($messageContent, function($message)
{
$message->to($foo->email);
});
This is what I want, in essence. $foo is a variable declared in the function that this is in. I don't want to make $foo a class variable because I am only using it here.
Thanks for helping!
Mail::raw($suggestionString, function($message) use ($follower)
{
$message->to('support#company.com')->subject('Suggestion')->replyTo($follower->email);
});
When you reply to this message it's automatically sent to the email specified in ->replyTo()
Related
I need to get laravel mail as variable and to pass in it model object
$markdown = new Markdown(view(), config('mail.markdown'));
$html = $markdown->render($template, $user->toArray());
Here is the problem I am not getting relations within array and I know that I can use with to pass relations, but I am wondering is there a better way of getting laravel mail as HTML variable?
Is there maybe I way to create new mail like PHP artisan make:mail Test and then to call that test mail class and get full filled mail as HTML?
Seems like doing this helps:
return (new Welcome(User::find(1)))->build();
This is returning mail html
I need to edit template which used for emails in admin panel. Any Ideas?
I think about several ways:
Save email template in DB in the text field, edit it in the admin panel and then display the text in the blade's view.
The problem of this way's realization is I have to display php variables in blade template and then use the final code as the html for email. I think, it's so difficult for Laravel.
And the additional problem is if I store {{ $var }} in template's text in DB - it will display as the text, blade compiler doesn't process it.
Store only the static text information from email in the DB and then display it in the template. PHP variables will transfer separately.
This way will solve the problem with the php var's display, but I still don't know how to use the final code in the Mail::send, because Laravel allows using the template's name only, not a HTML, as I know...
I think about the following way:
$view = view('template')->render();
mail(..., $view, ...);
But I don't want to use it because I want use Mail::queue() for querying emails and I don't know how to use it with PHP mail().
Thanks to everybody for replies.
You can create your own variable syntax and store email template as text in your DB. Foe example, you can store each variable as ${VARIABLE_KEY} string.
Then during email preparation you should resolve all such constructions into their real values. I don't know which variables are required, but during email preparation you should execute these steps:
Load email template from DB.
Replace all ${VARIABLE_KEY} with their real values.
You can use regular expressions for the searching and replacement, but also you can use functions such str_replace. For example, if you want to paste email of the current user into your email (and your table for model User has an email field), then you can create variable: ${user.name} and then replace this manually with simple str_replace function:
$variables['${user.name}'] = Auth::user()->email;
str_replace(array_keys($variables), array_values($variables), $yourEmailTemplateBody);
Also you can do replacements by the same method not only in the email template body, but in the email subject too.
Then you have to create your own class which extends Laravel Illuminate\Mail\Mailable class. In this class you should define build method, where you can use not only the name of the view, but also some additional parameters, like in the "regular" view, for example:
class SomeClassName extends Mailable
{
public function build()
{
$email = $this->view('mail.common', [
'mail_header' => 'some header',
'mail_footer' => 'some footer',
])->subject('Your subject');
...
return $email;
}
For example, in your view you can store layout for entire email with some extra parameters: footer and header as in my example.
Also you can create more complex syntax for ${VARIABLE_NAME} constructions, for example, VARIABLE_NAME can be a method definition in PHP or Laravel notation, i.e.: SomeClass::someStaticMethod. You can detect this case and resolve SomeClass via Laravel Service Container. Also it can be an object.field notation, for example, user.email, where user is the current Auth::user().
But be carefull in this cases: if you will grant ability to edit email templates with this variables for all users, you should filter fields or available methods and classes for calling to prevent executing any method of any available class in your email template or to prevent display private information.
You can read about writing mailables in Laravel documentation
I was doing this for a project yesterday and found a good post describing Alexander's answer in more detail. The core is creating an EmailTemplate model with this method:
public function parse($data)
{
$parsed = preg_replace_callback('/{{(.*?)}}/', function ($matches) use ($data) {
list($shortCode, $index) = $matches;
if( isset($data[$index]) ) {
return $data[$index];
} else {
throw new Exception("Shortcode {$shortCode} not found in template id {$this->id}", 1);
}
}, $this->content);
return $parsed;
}
Example usage:
$template = EmailTemplate::where('name', 'welcome-email')->first();
Mail::send([], [], function($message) use ($template, $user)
{
$data = [
'firstname' => $user->firstname
];
$message->to($user->email, $user->fullname)
->subject($template->subject)
->setBody($template->parse($data));
});
For all the details (db migration, unit test, etc), see the original post at http://tnt.studio/blog/email-templates-from-database
You can simply use this awesome laravel package:
https://github.com/Qoraiche/laravel-mail-editor
Features (from readme file):
Create mailables without using command line.
Preview/Edit all your mailables at a single place.
Templates (more than 20+ ready to use email templates).
WYSIWYG Email HTML/Markdown editor.
I'm using Laravel 5.3 to build an application which allows admins to build template emails to be used within the system for email address verification, forgot password etc. The template emails are built using a form which creates a new record in the database. Once the templates have been created they can be used within the application using the following command
Mail::to($user)->queue(new MailEmailTemplate($emailtemplate, $user));
where $emailtemplate is a model with the following fillable fields (there is nothing else worth disclosing within the model)
$fillable = ['from_name', 'from_email','subject','body','email_type','status'];
In order to allow the emails to be personalised to the user which they are being sent to (i.e. 'Dear John' at the top of the email body) I need to allow admins to enter variables into the form.
An example of how the form body should be filled out by the system admins:
Dear {{$user->first_name}}
Image of the form that admins will use to create the email template
The problem I am having is when the emails are sent the variables are not injected into the HTML sent to the client. i.e in the example above the recipient receives the email without the variables inserted
Dear {{$user->first_name}} as opposed to Dear John.
I have added the following route in my app/routes/web.php file
Route::get('/email_templates/{emailtemplate}/send/{user}', 'emailTemplatesController#send')->name('email_templates.send');
my App/Http/Controllers/emailTemplatesController.php
...
use App\Mail\MailEmailTemplate;
class EmailTemplatesController extends Controller
{
...
public function send(EmailTemplate $emailtemplate, User $user)
{
Mail::to($user)->queue(new MailEmailTemplate($emailtemplate, $user));
return back();
}
}
my app/Mail/MailEmailTemplate.php Mailable
use App\Models\User;
use App\Models\EmailTemplate;
use Session;
class MailEmailTemplate extends Mailable
{
use Queueable, SerializesModels;
public $user;
public $emailtemplate;
public function __construct(EmailTemplate $emailtemplate, User $user)
{
$this->emailtemplate = $emailtemplate;
$this->user = $user;
}
public function build()
{
$data['user'] = $this->user;
$data['email_template'] = $this->emailtemplate;
return $this->subject('testing')
->view('emails.index')
->with($data);
}
}
and finally the resources/views/emails/index.blade.php file (which is used to dislpay the email to the recipient)
{!! $email_template->body !!}
I've used unescaped output here as the text that is stored in the body field is HTML (admins will be developing the email template as a laravel 'view' in a text editor (phpStorm) then copy the code from the view into the form field for the body to store it within the application).
How can I modify this to allow the variables from the $user object to be inserted in place of the variables specified in the $emailtemplate->body?
If I modify the resources/views/emails/index.blade.php to the following the correct output can be achieved
{!! str_replace('<<$user->first_name>>',$user->first_name, $email_template->body)!!}
however this method is inefficient as it would require a str_replace to be used for any variable to be used within the emails. Note I've had to use << >> tags in the $email_template->body to prevent a parse error.
Update:
Could variable variables be used in conjunction with a regex to find every instance of {{ }} tags inside the $email_template->body and treat the text contained inside as a variable variable?
I apologise for the long question - I am relatively new to Laravel and wanted to make sure you guys could scrutinise my code structure.
Appreciate your help.
Jordan
try using
{{$email_template->body}}
Basically , I have a form and I want to send confirmation link after form posted , also I want to add all form fields and answers of users .I stored all data in my controller's store function and in the same function I wrote this mail function . However, I could not manage to add user's answers .
Mail::send('isim',['name'=>'email'],function($message){
$message->to('mail','mail')- >from('email','name')->subject('welcome');
});
Assuming that your user model has attributes name and a relationship to fetch answers called answers, You can do the following.
Here, Mail::send('isim',['name'=>$user->name,'answers'=>$user->answers] will inject $name and $answers to your view. You can access them there.
use ($user) will inject the $user variable to the function inside where you set the receiver's email address.
$user= //fetch user from the database as you wish
Mail::send('isim',['name'=>$user->name,'answers'=>$user->answers],function($message) use ($user){
$message->to('mail',$user->email)->from('email',"Your email address")->subject('welcome');
});
I'm trying to use database driver for queuing emails. Using Mail::send emails are sent as expected. But when I use Mail::queue the user object passed to the view gets null "Trying to get property of non-object".
I have a mailer class and these are the methods responsible for sending the email:
public function sendAssignmentEmail(User $user)
{
$this->to=$user->email;
$this->view='emails.assigned';
$this->data=compact('user');
$this->subject='subject';
$this->deliver();
}
public function deliver()
{
$to=$this->to;
$subject=$this->subject;
$from=$this->from;
return $this->mailer->queue($this->view,$this->data, function($message)
use($to, $subject, $from)
{
$message->from($from, 'example.com');
$message->to($to);
$message->subject($subject);
});
}
What am I doing wrong?
I know that the problem is with the
$this->data
If I pass an array the queue will work, but if the data is in form of an object it won't.
Mail::queue is essentially exactly the same as Mail::send except your queuing them to be sent.
As a result it expects the same parameters as Mail::send in which the second argument needs to be an array, hence why it works when you supply an array and doesn't when you supply an object.
Simply change $this->data=compact('user'); to be in the form of an array and it'll work fine for you.
The docs are super useful when you get stuck on things like this :).