How to attach created php excel to another function - php

I need to pass the gerenrated PHPExcel output to a function that will send it via Email. My current code is this:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
//Send Email here
$this->ciEngine->load->library( 'Services\Notifications\PushReports\Survey\Email' );
$emailResult = $this->ciEngine->Email->emailSurvey();
**UPDATE
I'm adding the emailSurvey's code for reference.
namespace Services\Notifications\PushReports\Survey;
use \Services\ServiceBase;
class Email
extends ServiceBase
{
public function emailSurvey( $countryConfig, $appointment )
{
if( empty( $appointment ) ) {
return false;
}
$this->ciEngine->load->library( 'email' );
$receipient = $this->ciEngine->config->config['push-report-receipient'];
$sender = $this->ciEngine->config->config['push-report-sender'];
if( !empty($receipient) && !empty($sender) ){
$this->ciEngine->email->initialize( $this->ciEngine->config->config );
$this->ciEngine->email->from( $sender );
$this->ciEngine->email->to( $receipient );
$this->ciEngine->email->subject( $this->ciEngine->config->config['push-report-subject'] );
ob_start();
$this->ciEngine->load->view( 'emails/surveyPush' );
$mailBody = ob_get_contents();
ob_end_clean();
$this->ciEngine->email->message( $mailBody );
return $this->ciEngine->email->send();
}
}
}
How could I pass it to the emailSurvey function?

Related

add an attachment in Xero using php Xero api

Can anyone help me add a pdf to a Xero Invoice using the official (non calcanai) PHP SDK. I'm connected with oAuth2 and have previously created a draft invoice.
I then update the invoice to Authorised and try to add an attachment to the invoice. At this point I am not getting any luck, the attachments is sent but comes back in the respose as null. The docs are not at all useful and do not give any examples of adding an attachment or even minimal fields. So this is what I have:
...
$attachments = $apiResponse->getInvoices()[0]->getAttachments();
$attachment = new XeroAPI\XeroPHP\Models\Accounting\Attachment;
$attachment->setFileName( $filename )
->setIncludeOnline( true )
->setMimeType( 'application/pdf' );
$attachments[] = $attachment;
$apiResponse->getInvoices()[0]->setAttachments( $attachments );
$apiResult = $accountingApi->updateOrCreateInvoices( $xeroTenantId, $apiAuth );
if ( !$apiResult->getInvoices()[0]->getHasAttachments() ) {
$errors[] = 'Pdf file was not added to Xero.';
}
$errorList = array();
$errList = $apiResult->getInvoices()[0]->getValidationErrors()[0];
if ( !is_null( $errList ) ) {
$errorList = $errList;
}
foreach ( $errorList as $err ) {
$errors[] = $err->getMessage();
}
if ( count( $errors ) == 0 ) {
$result['message'] = 'New Invoice Authorised: ' . $xeroInvoice->getReference();
$result['apiResult'] = $apiResult;
$result['success'] = true;
} else {
$result['message'] = print_r( $errors );
$result['success'] = false;
}
...
any ideas?
thanks
* CODE AFTER *
public function attachPDF( $xeroTenantId, $accountingApi, $invoice ) {
$filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
$guid = $invoice->invoice_id;
$content = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
$handle = fopen( $filename, "r" );
$contents = fread( $handle, filesize( $filename ) );
fclose( $handle );
unlink( $filename );
return $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
}
Adding an attachment requires two API calls.
// Create or Get your Invoice ID, then create Attachment
$invoices = $apiInstance->getInvoices($xeroTenantId);
$guid = $invoices->getInvoices()[0]->getInvoiceId();
// file in the same dir.
$filename = "./helo-heros.jpg";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$result = $apiInstance->createInvoiceAttachmentByFileName($xeroTenantId,$guid,"helo-heros.jpg",$contents);
Anyone else who has this same issue it is due to the filename having a # in it (AUTH#00000123.pdf in my example) the updated code based on sidneys answer is also the way forward

Send body content and calendar invite in an email

I am trying to send an email with both a calendar invite and HTML body content, but I can't seem to get the both added to the email object to be sent via SendGrid
I am able to send a calendar invite by itself and HTML body content by itself but not together.
function sendgridAPI(){
GLOBAL $mgClient,$domain,$toName, $toEmail, $fromName, $fromEmail, $subj, $body, $cc, $bcc, $attachments, $mimeMessage, $sendgrid_api_key;
$email = new \SendGrid\Mail\Mail();
$email->setFrom($fromEmail, $fromName);
$email->setSubject($subj);
$toEmails = [$toEmail => $toName,];
$email->addTos($toEmails);
if ($mimeMessage != ""){
echo "<br> 1 <br>";
$contents = [
"text/calendar" => $mimeMessage,
"text/html" => $body
];
$email->addContents($contents);
}
else{
$content = ["text/html" => $body];
$email->addContent($content);
}
if($cc != ""){
$ccEmails = [$cc => "CC",];
$email->addCcs($ccEmails);
}
if ($attachments != ""){
$filePath = $attachments;
$fileName = substr($attachments, strrpos($attachments, '/') + 1);
$fileData = base64_encode(file_get_contents($filePath));
$fileExtension = substr($attachments, strrpos($attachments, '.') + 1);
$fileType = 'application/'. $fileExtension;
$email->addAttachment(
$fileData,
$fileType,
$fileName,
"attachment"
);
$email->addAttachments($attachments);
}
$sendgrid = new \SendGrid($sendgrid_api_key);
try {
$response = $sendgrid->send($email);
$data = $response->headers();
print_r($data);
gettype($data['5']);
$responseSG = substr($data['5'], strpos($data['5'], ":") + 1);
return $responseSG;
//echo $responseSG;
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
return "";
}
}
?>
The variables are passed to this function then the email object is constructed to be sent using the SendGrid API
You need to create an attachment object for addAttachment(), not pass in a filename. And an array of Attachment objects for addAttachments()
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Mail.php#L1152-L1172
Here's the constructor for an Attachment:
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Attachment.php#L35-L52

Exclude email attachments from specific email notifications in Woocommerce

I would like to exclude added email attachments for customer reset password and customer new account emails, or limit adding some of attachment to Woocommerce order emails only (and exclude attachments for emails send to admin). Is it possible?
add_filter( 'woocommerce_email_attachments', 'doc_to_email', 10, 3);
function doc_to_email ( $attachments , $id, $object ) {
$attachments = array();
array_push($attachments, get_home_path() . '/doc/Zasady_ochrany_osobnich_udaju.pdf' );
if( !$id == array( 'customer_reset_password', 'customer_new_account') ) {
array_push($attachments, get_home_path() . '/doc/VOP.pdf' );
array_push($attachments, get_home_path() . '/doc/Reklamacni_rad.pdf' );
array_push($attachments, get_home_path() . '/doc/Reklamacni_protokol.pdf' );
array_push($attachments, get_home_path() . '/doc/Formular_pro_odstoupeni_od_smlouvy.pdf' );
}
return $attachments;
}
Thanks you
The following code will exclude email attachements from all admin email notifications and some attachements from specific email notifications:
add_filter( 'woocommerce_email_attachments', 'custom_email_attachments', 20, 3 );
function custom_email_attachments ( $attachments = [] , $email_id, $order ) {
// HERE define customer and admin excluded email Ids
$excluded_customer_email_ids = array( 'customer_reset_password', 'customer_new_account' );
$excluded_admin_email_ids = array( 'new_order', 'cancelled_order', 'failed_order' );
// Excluding attachements from admin email notifications
if( in_array( $email_id, $excluded_admin_email_ids ) )
return [];
$file_path = get_home_path() . '/doc/';
$attachments[] = $file_path . 'Zasady_ochrany_osobnich_udaju.pdf';
// Excluding some customer email notifications
if( ! in_array( $email_id, $excluded_customer_email_ids ) ) {
$attachments[] = $file_path . 'VOP.pdf';
$attachments[] = $file_path . 'Reklamacni_rad.pdf';
$attachments[] = $file_path . 'Reklamacni_protokol.pdf';
$attachments[] = $file_path . 'Formular_pro_odstoupeni_od_smlouvy.pdf';
}
return $attachments;
}
Code goes in function.php file of your active child theme (or active theme). It should works.

PHP returning extra whitespace with return statement?

My code works, but for some strange reason when I return a string it adds extra space and I think a new line as well.
The code below works fine. However the length of this when fetched with Ajax is 11, the string success has a length of seven so this isn't right and it also doesn't equal to 'success' when comparing.
I've looked through a few other questions but all the solutions they offer don't seem to be working for me. No trailing spaces anywhere as far as I can see. And it's also not coming from any of the files I'm requiring.
<?php
/*
Plugin Name: Quotation Rest API
Plugin URI:
Description: A rest API for sending quotation request through to email using Sendgrid.
Version: 1.0
Author: Niels
Author URI:
*/
add_action( 'rest_api_init', function () {
register_rest_route( 'offerte', '/send',array(
'methods' => 'POST',
'callback' => 'send_mail',
) );
} );
include('MailChimp.php');
use \DrewM\MailChimp\MailChimp;
function send_mail( WP_REST_Request $request) {
$data = $request['data'];
$name = htmlspecialchars($request['name']);
$email = htmlspecialchars($request['email']);
$comment = htmlspecialchars($request['comment']);
$website = htmlspecialchars($request['url']);
$company = htmlspecialchars($request['company']);
$tel = htmlspecialchars($request['tel']);
$mailchimp = htmlspecialchars($request['mailchimp']);
$dataArray = json_decode($data, true);
ob_start();
include('mail.php');
$mailHTML = ob_get_clean();
$success = 'success';
if (!empty($mailchimp)) {
// add email to mailchimp list
$client = new MailChimp('-us14');// get from setttings
$list_id = ' ';// get from setttings
$result = $client->post("lists/$list_id/members", [
'email_address' => $email,
'status' => 'subscribed',
]);
}
$to = " #icloud.com";// get from setttings
$subject = "Offerte van " . $name;// // get from setttings (maybe...)
$message = $mailHTML;
if(wp_mail( $to, $subject, $message)){
return $success;
} else {
// return 'error';
}
}
?>

add html ouput in joomla email

i am trying to set html on the output of the email send by joomla. my file is located in the joomla core.
i know i have to add something like ->isHTML(true); but i do not know where and how.
here is the code:
class MailtoController extends JControllerLegacy
{
/**
* Show the form so that the user can send the link to someone.
*
* #return void
*
* #since 1.5
*/
public function mailto()
{
$session = JFactory::getSession();
$session->set('com_mailto.formtime', time());
$this->input->set('view', 'mailto');
$this->display();
}
public function send()
{
// Check for request forgeries
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$session = JFactory::getSession();
$timeout = $session->get('com_mailto.formtime', 0);
if ($timeout == 0 || time() - $timeout < 1)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
$SiteName = $app->get('sitename');
$link = MailtoHelper::validateHash($this->input->get('link', '', 'post'));
// Verify that this is a local link
if (!$link || !JUri::isInternal($link))
{
// Non-local url...
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
// An array of email headers we do not want to allow as input
$headers = array (
'Content-Type:',
'MIME-Version:',
'Content-Transfer-Encoding:',
'bcc:',
'cc:'
);
// An array of the input fields to scan for injected headers
$fields = array(
'mailto',
'sender',
'from',
'subject',
);
/*
* Here is the meat and potatoes of the header injection test. We
* iterate over the array of form input and check for header strings.
* If we find one, send an unauthorized header and die.
*/
foreach ($fields as $field)
{
foreach ($headers as $header)
{
if (strpos($_POST[$field], $header) !== false)
{
JError::raiseError(403, '');
}
}
}
/*
* Free up memory
*/
unset ($headers, $fields);
$email = $this->input->post->getString('mailto', '');
$sender = $this->input->post->getString('sender', '');
$from = $this->input->post->getString('from', '');
$subject_default = JText::sprintf('COM_MAILTO_SENT_BY', $sender);
$subject = $this->input->post->getString('subject', $subject_default);
// Check for a valid to address
$error = false;
if (!$email || !JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $email);
JError::raiseWarning(0, $error);
}
// Check for a valid from address
if (!$from || !JMailHelper::isEmailAddress($from))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $from);
JError::raiseWarning(0, $error);
}
if ($error)
{
return $this->mailto();
}
// Build the message to send
$msg = JText::_('COM_MAILTO_EMAIL_MSG');
$link = $link;
//$body = sprintf($msg, $SiteName, $sender, $from, $link);
$body = "<p>Hello Test F,</p><br/><p>Thank you for registering at Deals&offers. Your account is created and activated.</p><br/>You may login to ".$SiteName." using the following username and password:</br><p>Username: ".$sender."</p><p>Password: ".$from."/p><br/><p><b>Note:</b> It is recomended to change your password after first login. ".$link."</p>";
// Clean the email data
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
// To send we need to use punycode.
$from = JStringPunycode::emailToPunycode($from);
$from = JMailHelper::cleanAddress($from);
$email = JStringPunycode::emailToPunycode($email);
// Send the email
if (JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body) !== true)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
JFactory::getApplication()->enqueueMessage('ok!', '');
$this->input->set('view', 'sent');
$this->display();
}
}
thank you very much
you can add before body or between subject and body . however, it must be before the submit command !!
here is an example of PhpMailler firstly, you need to call the class like this and you can use it
$this->mail= new PHPMailer();
$this->mail->IsSMTP();
$this->mailIsHTML(true);
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
however if the function is static also you call the function in same class
you can call the function by sef command
self::mailIsHTML(true)

Categories