Email an image created on HTML5 canvas - php

I have a canvas which user can interact to make changes to design. Now after the user is done with his changes he can submit his design along with his email ID. But to submit the design i am converting the canvas to an image using http://www.nihilogic.dk/labs/canvas2image/
Now i want to send this image along with user's email ID. How can i send this image directly without letting user save it on his local system.

I'm thinking you need some javascript magic, and because you already use HTML5 canvas, that shouldn't be a problem.
So, an onclick event on the submit button that will make an ajax request to your backend php mailer script.
var strDataURI = oCanvas.toDataURL();
// returns "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."
You just have to pass the strDataURI as a parameter.
Now, I think you should also save these in your database, so that the email can just contain this image tag inside:
<img src="http://www.yourdomain.com/generate_image.php?id=2" alt="Design #2" />
And that the generate_image.php script will do something like this
<?php
header('Cache-control: max-age=2592000');
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 2592000));
// connect to db here ..
// $id = (int)$_GET['id']; "SELECT youtable WHERE id = '{$id}'"
// and the $image variable should contain "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."
list($settings, $encoded_string) = explode(',', $image);
list($img_type, $encoding_method) = explode(';', substr($settings, 5))
header("Content-type: {$img_type}");
if($encoding_method == 'base64')
die(base64_decode($encoded_string)); // stop script execution and print out the image
else { // use another decoding method
}

if(!empty($_POST['email'])){
$email=$_POST['email'];
$image=$_POST['legoImage'];
$headers="From:".$email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
list($settings, $encoded_string) = explode(',', $image);
list($img_type, $encoding_method) = explode(';', substr($settings, 5));
if($encoding_method == 'base64'){
$file=fopen("images/newLego.png",'w+');
fwrite($file,base64_decode($encoded_string)) ;
fclose($file);
}
$my_file = "newLego.png";
$my_path = "images/";
$my_subject = "My Design";
$my_message = "Designed by ".$email;
mail_attachment($my_file, $my_path, "myemail#gmail.com", $email, $email, $email, $my_subject, $my_message);
}
I picked up the mail_attachment() function here.

Assuming you've succeeded in creating an image file of your canvas using the tutorial you posted, you can use a library like PEAR's Mail_Mime to add attachments to your email.
You can refer to this question for an example using Mail_Mime.

Related

PHP - My code does not work. Am I using include wrong?

My question has differently been answered in another post, but I just can't make things work with my own code - so here it comes:
I am making a reminder function, that is supposed to be executed by cron job and send out an reminder email to remind client about an event.
I will use info from mysql, sort out the events that is going to be reminded based on X number of hours and the reminder time frame (if the cron job runs every 15 minutes, the code must find all event starting in the minutes between each cron job run).
All the above works just fine, and I do get the echo "test1"; from test-cron.php. But the email from test-cron-email-reminder.php is not send, and I do not get the echo "test2"; printed out.
I seems like my include in test-cron.php does not work. Why?
If I put it all together in one php file it works fine.
When this is ready, I will make a similar code to send out sms reminder with twilio. That as well works fine, as long as the whole code is in one file.
Both php files are in the same folder.
Here is my code:
TEST-CRON.PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Get info from SQL
$result = performQuery("SELECT mindful_pbbooking_events.service_id,
mindful_pbbooking_treatments.id,
mindful_pbbooking_events.id, name,
customfields_data,
dtstart, dtend, date_created
FROM mindful_pbbooking_events,
mindful_pbbooking_treatments
WHERE
mindful_pbbooking_events.service_id=mindful_pbbooking_treatments.id;
");
while ($row = mysqli_fetch_array($result)) {
//Split customfields_data and collect the informaton from created array (just making things a little bit more easy to work with)
$dataArray = $row[customfields_data];
$dataArrayDecoded = json_decode($dataArray,TRUE);
$clientFname = $dataArrayDecoded[0][data];
$clientLname = $dataArrayDecoded[1][data];
$clientEmail = $dataArrayDecoded[2][data];
$clientMobile = $dataArrayDecoded[3][data];
$clientGender = $dataArrayDecoded[4][data];
//Collect information from customfields_data (more making things a little bit more easy to work with)
$eventId = $row[mindful_pbbooking_events.id];
$eventStart = $row[dtstart];
$eventDate = date("Y-m-d", strtotime($eventStart));
$eventTime = date("H:i", strtotime($eventStart));
$eventEnd = $row[dtend];
$service = $row[name];
$eventCreated = $row[date_created];
//Time calculation to find out who to send reminder to
$eventtimestring = strtotime("$eventStart");
$nowtimestring = strtotime("now");
$reminderdurationstring = $reminderDuration*60;
$startstring = $nowtimestring + $hours*3600;
$endstring = $startstring + $reminderdurationstring;
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
// ****** HERE IT COMES ******
// The test-cron-email-reminder.php is the file with the code I want to include
include 'test-cron-email-reminder.php';
}
}
?>
TEST-CRON-EMAIL-REMINDER-PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
break;
?>
require 'configuration.php';
in TEST-CRON-EMAIL-REMINDER-PHP
may produce redeclaration error
try require_once 'configuration.php';
to prevent it
The problem is in TEST-CRON.PHP -- don't put an include inside a while loop, unless you really want to include that file over and over. (You don't)
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
/// DON'T DO THIS
include 'test-cron-email-reminder.php';
/// DON'T DO THIS
}
Instead, do this. In TEST-CRON.PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
require_once 'TEST-CRON-EMAIL-REMINDER-PHP'
...
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
doSomething(); // Defined in TEST-CRON-EMAIL-REMINDER-PHP
break;
}
In TEST-CRON-EMAIL-REMINDER-PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// And wrap all this stuff up in a function that
// you can call from within your while() loop.
func doSomething() {
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
}
?>

wp_mail() - Sending 'file' input type from form as attachment

I have shortcode that creates and validates a form in my fucntions.php file. After the form is submitted and validated, the data is then stored in SESSION variables. The SESSION variables are used to carry the information to a custom PHP template page. This page emails the form data using wp_mail() and displays a thank you note.
My issue is that the form has a 'file' input type for an image upload. I have it validated correctly, but transferring the uploaded image and then emailing it as an '$attachments" in the wp_mail() function is something I am struggling with.
Also I know I should save the uploaded image in a temp folder instead of storing it in a SESSION variable. And then I will just have to delete the image after the email is sent.
My question is HOW? The code for all of this is very long so here are the short and sweet versions:
functions.php (in a shortcode function)
<?php
$file = "";
$fileErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//file upload is required, make sure its not empty
if(empty($_FILES['pmFile'])){
$fileErr = "This is required!";
}
else{
$file = $_FILES['pmFile'];//I validate here, but lets just say its OK
}
//If the error message is empty, store data in SESSION variables, and
//uploaded file in temp folder + redirect to thank you page
if(empty($fileErr)){
//HOW DO I SAVE THE FILE TEMPORARILY FOR USE ON THE NEXT PAGE???
wp_redirect( '../wp-content/themes/rest of the path/thankYouPage.php' );
exit();
}else{ /*display errors*/}
}
//down here is where I wrote the code for the form. YES method=post, YES I
//included enctype="multipart/form-data, YES the file input name is in fact
//'pmFile'.
?>
thankYouPage.php
//initial page stuff
//start email setup
$to = 'XXXXX#gmail.com';
$email_from = 'XXXXX#gmail.com';
$email_subject = "New Price Match Request";
$email_body = "I display the html and data here";
//for attachments
//HOW DO I PULL THAT UPLOADED FILE FROM THE TEMP FOLDER AND SEND IT AS AN ATTACHMENT?
$attachments = (the file in temp folder);
//NOW HOW TO I DELETE IT FROM THE TEMP FOLDER
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n"; //$email is a SESSION variable pulled from before
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//set to html
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
//send
wp_mail( $to, $email_subject, $email_body, $headers, $attachments );
// Reset content-type to avoid conflicts
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
I know a lot of the code it removed, but email works for all of the other information in the form being transferred by SESSION variables. I really just need to know how to transfer this uploaded file and email it. Thanks!
If I understood correctly...
For uploading file from temp folder use move_uploaded_file or wp_handle_upload.
Then attach file to the mail $attachments = array( WP_CONTENT_DIR . '/uploads/file.txt' );
Send mail and delete with unlink.
I would just use PHPMailer, its pretty easy and has a good documentation, sending an attachment is also easy with that.

How to send wp_mail with attachment (file-path in variable)

i want to send an email with attachment using wordpress' wp_mail function.
With this function it works fine to send emails but the attachment isn't there when i check my email.
function dd_send_email(){
$dd_path = $_POST['upload_image'];
// echo $dd_path;
$email_sent = false;
// get email template data
$email_template_object = dd_get_current_options();
// if email template data was found
if ( !empty( $email_template_object ) ):
// setup wp_mail headers
$wp_mail_headers = array('Content-Type: text/html; charset=UTF-8');
$mail_attachment = $dd_path;
// use up_mail to send email
$email_sent = wp_mail( array( 'example#mail.no') , $email_template_object['dd_emne_forhaandsbestilling'], $email_template_object['dd_email_text_forhaandsbestilling'], $wp_mail_headers, $mail_attachment );
endif;
return $email_sent;
}
The variable $dd_path (something like: http://localhost/norskeanalyser/wp-content/uploads/Testanalyse-2.pdf) contains the path of the file which i do upload from the media uploader in another function.
Thanks for your help!
I did found the answer by myself. Because wp_mail needs the file path like this /uploads/2016/03/example.jpg we have to convert our url to a path like this.
I did achive this by doing the following and thought i can share it with you:
// change url to path
$dd_url = $_POST['upload_image'];
$dd_path = parse_url($dd_url);
// cut the path to right directory
$array = explode("/norskeanalyser/wp-content", $dd_path['path']);
unset($array[0]);
$text = implode("/", $array);
and then i did save the $text into $mail_attachment and called it in wp_mail like above.

Upload notification

I am using EFUMultiple Uploader to receive files on my site. Does anyone know of a tutorial that will teach me how I can be notified each time there is a new file or batch of files in my uploads folder?
It will become annoying, fast, I can promise you that.
But either way, in your upload script, you'll want to use either the mail() function or, for example the PHPMailer library if you don't have a SMTP server configured on your PHP installation.
Consider this (untested) script:
#!/usr/bin/env php
<?php
// Warning: this script and UPLOADED_FILES_DB, for security reasons, should not be in UPLOAD_PATH.
define('UPLOAD_PATH', '...');
define('UPLOADED_FILES_DB', 'uploaded_files');
define('MAIL_TO', 'you#example.com');
define('MAIL_FROM', 'cron#example.com');
define('MAIL_SUBJECT', 'Uploaded files');
// Get old files:
if (file_exists(UPLOADED_FILES_DB)) {
$old_files = unserialize(file_get_contents(UPLOADED_FILES_DB));
} else {
$old_files = array();
}
// Get current files:
$current_files = array();
foreach (new DirectoryIterator(UPLOAD_PATH) as $file_info) {
if (!$file_info->isDot()) {
$current_files[$file_info->getFilename()] = filemtime($file_info->getFilename());
}
}
// Update database:
file_put_contents(serialize($current_files), UPLOADED_FILES_DB);
// Compute differences:
$added_files = array_diff(array_keys($old_files), array_keys($current_files));
$removed_files = array_diff(array_keys($current_files), array_keys($old_files));
$changed_files = array_diff_assoc($old_files, $current_files);
// Send message:
$headers = 'From: ' . MAIL_FROM . "\r\n";
$message = 'Added files: ' . implode(', ', $added_files);
mail($to, $subject, $message, $headers);
Then you would put that script on a cron job to execute every day or so, or you can include it in wherever your upload code is — though, the latter approach would get annoying quickly.

Php mail() breaks 650 char long Url

Im using the php mail function to send a link with many many paramaters. The url after being encoded can be 650 or more characters long because its holding variables to repopulate a form.
When I click on the link in my email its broken because a space has been inserted somewhere in the URL.
Heres my sendMail function:
protected function sendEmail($to, $subject, $body) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . '\r\n';
$headers .= 'From: Sales Order From <sales#imninjas.com>' . '\r\n';
$headers .= 'X-Mailer: PHP/' . phpversion() . '\r\n';
$body = '<html><body style="font-size: 10pt; font-family: Arial, Helvetica, sans-serif;">'.$body.'</body></html>';
return mail($to, $subject, $body, $headers);
}
Heres the code I call sendMail with. Its the '$salesUrl = $this->getSalesFormUrl();' that is the 650+ character url chock full of encoded paramaters.
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$salesUrl."'>".$salesUrl."</a><br/><br/>";
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And here's the URL I receive in my email, you'll notice the space '...BhsNKq Jsd_x4...' in the middle of the URL. This happens in a different place each time even if I'm sending the exact same url. To prove this I hard coded this url without a space in the emailRep method and sent it multiple times. The space moved around.
http://example.com/admin/index.php?fdJdj9QgFAbgXzPcNJ3AAdbxgotxdk28cNRMjPESW9yihVbKxHR_vaeU7TSZxqSfHDhPX9Jg-lPneu1H9cFHE7yJxUcdfpto_XNxtv6XHkgw_Vk7oy7aFRdnYzONPDltWxV01Zi23glqnU-z91XnpvrnpvNGSXYo4Q0t6UEKUmUp9Sh28JC7Va01Pmaibcc83M8dpCzzKYn5H_rX_BhsNKq Jsd_x4w7e4zHqputSWdc1Uwzezt2LS5xGQJHKxlF98qbzUZMhauxw_k5ebK8YPwDFr776GEb11WPzGtfhjIFE68zL9H2l3FOCFXea5qkHUmO9pCihThlegDLAHamuIeCmTiXSGv8cm_TorL-6q8NnYuvp6nEfpntthgrvx3enkhWP-FJ0P4vYYAvyJ45pbR9slaw9pbPLsnu4d9nNZSuXJZdll2WXJRc2XKYgu0zRvcwuqBSVwuzylQu4ILugxOJCciG7kF1Qx8vjZl5Y8sIqL59dRu9dfnP5yuXJ5dnl2eXJ3crLl7x8lVeoFJWKe1co_uoK_B1eXZFckV2RXaG-fHvazCuWvGKVV84u23DlzZUrVyZXZldmVyZ3K69c8so57z8
Here is the code I use to encode / decode the url paramaters before sending it through the email.
class UrlEncoder {
function compressUrl($url) {
return rtrim(strtr(base64_encode(gzdeflate($url, 9)), '+/', '-_'), '=');
}
function uncompressUrl($url) {
$startParams = strrpos($url, "?");
if($startParams) {
$paramaterString = substr($url, $startParams);
$host = substr($url, 0, strrpos($url, "?"));
$uncompressedParamaters = gzinflate(base64_decode(strtr($paramaterString, '-_', '+/')));
return $host."?".$uncompressedParamaters;
} else {
return NULL;
}
}
}
How do I prevent this space? I know I could shorten the URL with something like bit.ly however its an internal tool. I feel like there must be a way to stop the space from being inserted.
Who in their right mind uses a 650-character long query string?
My recommendation is to save the query-string server-side. Put it in a database with an AUTO_INCREMENT field, then you can get an ID for it. Then you can just send the URL as http://example.com/?email_key=ID_GOES_HERE, a much shorter URL. Then just look up the query string from the database.
Done.
I have what you need, http://www.9lessons.info/2009/01/split-url-from-sentence-using-php.html. Create tinyurl links using API,nothing in the database :)
Ok,I had same issue. My solution was my own link shrinking... Make new table in database with few rows, few lines of code in your old script, and new page for redirect... This is shortest explanation, if you need some help,just ask :)
EDIT:
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
/***********************************************************************************/
$arr = str_split('QWERTYUIOPLKJHGFDSAZXCVBNM123456789qwertyuioplkjhgfdsazxcvbnm'); // get all the characters into an array
shuffle($arr); // randomize the array
$arr = array_slice($arr, 0, 6); // get the first six (random) characters out
$short = implode('', $arr); // smush them back into a string
mysql_query("INSERT INTO shortlinks VALUES(NULL, '$salesUrl', '$short')");
/*******************************************************************************************/
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$short."'>".$short."</a><br/><br/>"; // Rename $salesUrl to $short
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And redirect page:
$token=$_GET['token']; // like http://example.com/out.php?token=ahgByT or make it cleaner with htaccess
$qry=mysql_query("SELECT * FROM links WHERE short='$token'");
$arr=mysql_fetch_array($qry);
$out=$arr['long_link'];
header("Location: ".$out);
?>

Categories