Laravel mail to variable with user model params passed - php

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

Related

How to send params in compose method of mailer yii2

I'm trying to send one param ($id) to view layout\html.php using compose() method of mailer component. But i don't know how to get it
The code:
$id = 1;
Yii::$app->mailer->compose('\layouts\html.php', ['id' => $id])
->setFrom('stackfrom#gmail.com')
->setTo('stackto#gmail.com')
->setSubject('Email sent from Yii2-Swiftmailer')
->send();
And in a line of my view layout\html.php
<div><?php echo $id ?></div>
Error is here!
You don't call a view file with compose() method like this, you should use alias like #common, #frontend or any other relevant to the view you are trying to load mostly we place all views related to emails in common/mail so we will use #common alias in example.
You can use 2 ways
You may pass additional view parameters to compose() method, which will be available inside the view files.Yii::$app->mailer->compose('#common/path/to/view', ['id' => $id]);
Render HTML separately
$body =Yii::$app->view->renderFile('#common/path/to/view-file.php',['id'=>$id])
to render the HTML from the php file, pass it any parameters you want to like any normal view file and then attach it to the email body using setHtmlBody($body), use the following way
$body = Yii::$app->view->renderFile ( '#common/mail/account-activation.php' , [
'id' => $id
] );
Yii::$app->mailer->compose()
->setFrom('stackfrom#gmail.com')
->setTo('stackto#gmail.com')
->setSubject('Email sent from Yii2-Swiftmailer')
->setHtmlBody($body)
->send()
For more help see Documentation
Compose method takes special alias in format '#app/mail/layouts/default.php'
So if you are using absolute format, use # and path (yii2 aliases)
Reference to swift mailer you can see here: http://www.yiiframework.com/doc-2.0/yii-swiftmailer-mailer.html

PHP Laravel Sending email inside variable to Mail::raw

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()

Edit email template in Laravel

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.

laravel 5.1 database queue not working

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 :).

send email from model and template

if i want send email with SwiftMailer in symfony then i must in action:
$message = $this->getMailer()->compose(
array('user#gmail.com' => 'user'),
$affiliate->getEmail(),
'Jobeet affiliate token',
body
);
$this->getMailer()->send($message);
but this doesnt working in template and in model (i would like create function for this).
I wouldn't recommend sending mail using a template - put a link in the template and call the action to send the mail ... you can send from a model although again i wouldn't recommend it as using sfContext::getInstance() inside the model is a really bad practice as it makes the model class rely on the context. So, your model class can't be unit tested as it needs a context to work...
You need an instance of the current sfContext to do it ... i would suggest passing it as a parameter when you create the model

Categories