Reputation: 3141
This is how I can generate pdf page
public function actionPdf(){
Yii::$app->response->format = 'pdf';
$this->layout = '//print';
return $this->render('myview', []);
}
And this is how I send emails
$send = Yii::$app->mailer->compose('mytemplate',[])
->setFrom(Yii::$app->params['adminEmail'])
->setTo($email)
->setSubject($subject)
->send();
How I can generate pdf as a file and attach it to my emails on the fly?
Upvotes: 5
Views: 6027
Reputation: 6539
This is how I sent mails in Yii2
private function sendPdfAsEmail($mpdf)
{
$mpdf->Output('filename.pdf', 'F');
$send = Yii::$app->mailer->compose()
->setFrom('[email protected]')
->setTo('[email protected]')
->setSubject('Test Message')
->setTextBody('Plain text content. YII2 Application')
->setHtmlBody('<b>HTML content.</b>')
->attach(Yii::getAlias('@webroot').'/filename.pdf')
->send();
if($send) {
echo "Send";
}
}
mpdf
instance to our custom function.F
option in mpdf
to save the output as a file.attach
option in Yii mailer and set the path of the saved file.Upvotes: 1
Reputation: 5031
Mailer have method called attachContent()
, where you can put pdf file.
PDF should be rendered with output destination set as string, and then pass it as param to attachContent()
.
Sample:
Yii::$app->mail->compose()
->attachContent($pathToPdfFile, [
'fileName' => 'Name of your pdf',
'contentType' => 'application/pdf'
])
// to & subject & content of message
->send();
Upvotes: 7
Reputation: 3141
This is how I did it
In my controller:
$mpdf=new mPDF();
$mpdf->WriteHTML($this->renderPartial('pdf',['model' => $model])); //pdf is a name of view file responsible for this pdf document
$path = $mpdf->Output('', 'S');
Yii::$app->mail->compose()
->attachContent($path, ['fileName' => 'Invoice #'.$model->number.'.pdf', 'contentType' => 'application/pdf'])
Upvotes: 4