Swiftmailer pdf attachment from snappy bundle - php

I have an function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request).
This function downloads a pdf with information from objects everything works fine.
This is the function:
public function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request): Response
{
//search id
$workOrder = $this->getDoctrine()->getRepository(WorkOrders::class)->find($id);
//data to pdf template
$html = $this->renderView('pdf/pdf.html.twig', array(
'workOrder' => $workOrder,
));
//name file
$filename = $workOrder->getId();
//download pdf
return new PdfResponse(
$snappy->getOutputFromHtml($html),
$filename.'.pdf'
);
}
And then I have an swift mailer function:
//check if signed and if check is true
if ($data_uri) {
//send workOrder to company
if ($check == true) {
$transport = (new \Swift_SmtpTransport('smtp.sendgrid.net', 587))
->setUsername('sendgridUSERNAME')
->setPassword('sendgridPASSWORD')
;
$mailer = new \Swift_Mailer($transport);
$message = (new \Swift_Message('Werkbon '.$workOrder->getTitel()))
->setFrom(['xxx' => 'xxx'])
->setTo('xxx')
->setBody('xxx')
->attach(\Swift_Attachment::fromPath($this->downloadPdf()))
;
$result = $mailer->send($message);
}
The email works fine but I want to attach the pdf from the other function to this email in the code above you can see what I tried but I think I got it totally wrong.
I have no idea where to start.
Can someone give me a little push in the right direction?
Thanks!

here is how it works for me,
$invoicepdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($html);
/* And instead of returning pdf, send it with mailer: */
$message = \Swift_Message::newInstance()
->setSubject('YOUR_TITLE')
->setFrom('foo#from.net')
->setTo('foo#to.net')
->attach(\Swift_Attachment::newInstance($invoicepdf, 'your_file_name','application/pdf'))
->setBody("yyy");
$mailer->send($message);

Related

Userfrosting ExtendedMailMessage not clearing attachments

I am using the ExtendedMailMessage class to try and send an email with an attachments to my clients. The issue is I am sending the email inside a foreach loop and for some reason even though I am defining a new attachment the new attachment is just being appended to an array and each client gets multiple attachments instead of one.
$extendedMailer = $this->ci->extendedMailer;
foreach ($emails as $email) {
$attachment = new MailAttachment(
base64_decode($base64String), "report.pdf"
);
try {
$message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');
$message->from($config['address_book.admin'])
->addEmailRecipient(new EmailRecipient($email, 'Client'))
->setFromEmail($config['address_book.admin'])
->setReplyEmail($config['address_book.admin'])
->addAttachment($attachment);
$extendedMailer->sendDistinct($message);
}
catch(\Exception $ex) {
var_dump($email);
}
}
The first client will receive 1 attachment and then the 2nd will receive 2 attachments, 3rd will receive 3 attachments etc...
How do I just send 1 attachement with each email instead of appending it to the old attachments
Since PHPMailer instance is reused for each email, anything set on PHPMailer is carried on to the next email. When the Mailer's send or sendDistinct methods are called, only the recipients are explicitly cleared. So in your case, you might need to explicitly clear the attachement from $message between each email (depending how your addAttachment is implemented).
Another solution might be to move the addAttachment call outside the loop, assuming each email as the same attachement :
$extendedMailer = $this->ci->extendedMailer;
$attachment = new MailAttachment(
base64_decode($base64String), "report.pdf"
);
$message = new ExtendedTwigMailMessage($this->ci->view, 'mail/pdf-reports.html.twig');
$message->from($config['address_book.admin'])
->setFromEmail($config['address_book.admin'])
->setReplyEmail($config['address_book.admin'])
->addAttachment($attachment);
foreach ($emails as $email) {
try {
$message->addEmailRecipient(new EmailRecipient($email, 'Client'));
$extendedMailer->sendDistinct($message);
}
catch(\Exception $ex) {
var_dump($email);
}
}
Note that the following fix will be introduced in UserFrosting V5 send/sendDistinct to avoid this issue :
// Clone phpMailer so we don't have to reset it after sending.
$phpMailer = clone $this->phpMailer;

Unable to move mails to sent folder of IMAP using Laravel

I am sending emails from my laravel website using SMTP. When i send email to the user then i want to copy that mail to IMAP sent folder too.
Here is my code when i am sending mail to user:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
$result = imap_append($imapStream,$path,$mail->getSentMIMEMessage());
imap_close($imapStream);
Also I tried using imap_mail_move() method like so:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
imap_mail_move($imapStream,$mail,$path);
imap_close($imapStream);
Both ways it didn't worked out
In ComplaintMail class, build function looks like :
public function build()
{
return $this->from($this->sender)
->subject($this->subject)
->markdown('emails.complaint');
}

Symfony, swiftmailer, incorrect email

I use swift mailer for send email, and after send email in box I have mail without html, like in screen
but in another mail services everything fine
this my code
public function createMessage($subject, $receivers, $template, $context)
{
$message = \Swift_Message::newInstance($subject);
$message->setFrom($this->from_address);
$message->setTo($receivers);
$body = $this->twig->render($template, $context);
$plaintext = strip_tags($body);
$message->setBody($body, "text/html");
$message->addPart($plaintext, "text/plain");
$this->mailer->send($message);
}
What problem in this code? I set body test/html. What problem not understand
Try with this:
public function __construct(Container $oContainer) {
$this->oContainer = $oContainer;
}
$this->oContainer->get('templating')->render()
And set the content yourself:
$message->setContentType('text/html');

How to send SMS on php Textlocal.in api

I have used this code for send OTP on Given number. but can't send SMS. how to solve this....
PHP code
<?php
require_once ('smartysettings.php');
require_once ('class/User.php');
require_once ('class/Sms.php');
require_once ('class/RandomNumber.php');
$number = $_POST['mobnum'];
$result = #User::GetUserIdORMobile($number);
if($result->database->rows = 1)
{
$otp = RandomNumber(10);
$message = "Your OTP(One Time Password) is '$otp'";
$sender = 'Minveedu';
//print_r($otp); exit;
#Sms::SmsSend($number,$message,$sender);
}
?>
major class file for send SMS
PHP code
<?php
require_once ('textlocal.class.php');
class Sms
{
var $sms;
var $textloc;
public function __construct()
{
$this->textloc = new Textlocal('*******************', '****************');
}
public static function SmsSend($number,$message,$sender)
{
$ins = new self();
$numbers = array($number);
return $ins->textloc->sendSms($numbers,$message,$sender);
}
}
?>
how to solve and send SMS. please help for this request.
they themselves provide the code in php to send sms, you can find it by logging into your account then navigate HELP >> All DOCUMENTATION >> here you will find the copy and paste code section. just go through and it will work

Sending an email using a template file

I am trying to figure out the best way to send emails from an external template file, at the moment I have a template file that looks like this:
Thank you, your order has been received, someone will review it and process it. No money has been taken from your account.
<?php
echo date('Y-m-d H:i:s');
?>
<pre>
<?php print_r($this->data); ?>
</pre>
And then my send method looks like this:
public function notify($template) {
// get the template from email folder
$path = $_SERVER['DOCUMENT_ROOT'].'templates/email/'.$template.'.php';
if(file_exists($path)) {
ob_start();
require_once($path);
$body = ob_get_contents();
ob_end_clean();
$subject = 'email send';
foreach($this->emailTo as $email)
new Mail($email,$subject,$body);
}
}
This all works fine when I call it like this:
$notifications = new notifications();
$notifications->setData(array('order' => $order->order));
$notifications->addEmail($order->order->email);
$notifications->notify('orderReceived');
However, if I try to make two calls to the "notify" method then the second email is blank, I know this is because the object buffer, but I cannot think of any other way to do it.
Thanks,
Ian
You are using require_once, so the file will only load once. Try require.
Also consider loading a pure text template and use str_replace to replace the variables in the template like this:
$template = "<pre>%DATA%</pre>";
$text = str_replace('%DATA%', $this->data, $template);
I would do this:
Template file
Thank you, your order has been received, someone will review it and process it. No money has been taken from your account.
%s
<pre>
%s
</pre>
Notify function
public function notify($template) {
// get the template from email folder
$path = $_SERVER['DOCUMENT_ROOT'].'templates/email/'.$template.'.php';
if (!file_exists($path)) {
// Return false if the template is missing
return FALSE;
}
// Create the message body and subject
$body = sprintf(file_get_contents($path), date('Y-m-d H:i:s'), print_r($this->data, TRUE));
$subject = 'email send';
// Send the mail(s)
foreach($this->emailTo as $email) {
new Mail($email, $subject, $body);
}
// Return true for success
return TRUE;
}
This will solve the problem - which could be solved anyway by changing require_once to require.
Using require_once means the template file will only be loaded once (clue's in the function name), so the second call will result in a blank body.

Categories