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

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.

Related

How do I attach a Word (docx) file I made using a template processor into an email I'm sending

I'm using this function to send a mail, and it works perfectly:
mail('emailhere','subjecthere','contenthere');
I'm also using this code to create a word file and offer the user to download it:
// I use my templace that's with my files :
$templateProcessor = new TemplateProcessor('Template.docx');
// I fill the template values from an sql query :
$templateProcessor->setValue('titre', $options['titre']);
$templateProcessor->setValue('source', $options['source']);
$templateProcessor->setValue('auteur', $options['auteur']);
$templateProcessor->setValue('date_pub', $options['date_pub']);
$templateProcessor->setValue('contenu', $options['contenu']);
// I give the user the file (I don't fully understand how this works but it does)
header("Content-Disposition: attachment; filename=$title.docx");
$templateProcessor->saveAs('php://output');
What I'm trying to do is, I want to create a word file from that template, put it inside that mail and send it
I apologize for the lack of code that I tried, but I really don't know where to start even.
I have been recommended to use this:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you#example.com', 'Your Name'); //Name is optional
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress( 'destinationaddress#example.com' );
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );
return $email->Send();
But I don't know what the path to the file is?
Add the following lines of code:
// Create a temporary file to store the template.
$temp_file = tempnam(sys_get_temp_dir(), 'PHPTemplate');
// Save the template
$templateProcessor->saveAs($temp_file);
// Attach the temporary file (template) to the email
$mailer->addAttachment($temp_file, 'nameofile.docx');
// Send Email
return $email->Send();

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.

PHP Direct SMTP Send + Attachment

I'm using xpertmailer to send email direct to the remote SMTP server following an MX lookup. This works really well and works on an old closed source NAS drive running PHP4 and on current PHP5 boxes.
<?php
define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors
require_once '/path-to/SMTP.php'; // path to 'SMTP.php' file from XPM4 package
$f = 'me#mydomain.net'; // from mail address
$t = 'client#destination.net'; // to mail address
// standard mail message RFC2822
$m = 'From: '.$f."\r\n".
'To: '.$t."\r\n".
'Subject: test'."\r\n".
'Content-Type: text/plain'."\r\n\r\n".
'Text message.';
$h = explode('#', $t); // get client hostname
$c = SMTP::MXconnect($h[1]); // connect to SMTP server (direct) from MX hosts list
$s = SMTP::Send($c, array($t), $m, $f); // send mail
// print result
if ($s) echo 'Sent !';
else print_r($_RESULT);
SMTP::Disconnect($c); // disconnect
?>
I'm now trying to add an attachment to it, but I've no idea how to get an attachment to be included and sent.
Anyone any ideas how I can do this ?
Thanks
Example:
$m = new MAIL;
// attach source
$a = $m->Attach('text message', 'text/plain');
$f = '/path/image.gif';
// attach file '$f', disposition 'inline' and give a name 'photo.gif' with ID value (this ID value can be used in embed HTML images)
$a = $m->Attach(file_get_contents($f), FUNC::mime_type($f), 'photo.gif', null, null, 'inline', MIME::unique());
echo $a ? 'attached' : 'error';

How to hook inside a function in wordpress

I got a plugin (kind of sign up form), that offers developers some actions/hooks to add their own stuff. Inside the plugin the function is called like this:
// Allow devs to hook in
do_action( 'after_record_action', $result, $data, $format );
I guess that $data is an array storing the form data. After a visitor uses the signup form I want to send a mail containing $data using wp_mail()
How can I execute the following script using after_record_action? Do I need to add this inside my functions.php?
// get data from $data[] array
$data['email'] = $email;
$data['key'] = $key;
// use $data to create a personalized mail
$to = $email;
$subject = "Wordpress Test";
$content = "Hi, this us your key:" . $key . "Enjoy using it!";
// send mail using wp_mail
$status = wp_mail($to, $subject, $content);
I appreciate any help in combining these, as I am not too experienced using php.
Add following code into your currently active theme's functions.php file:
add_action('after_record_action', 'marian_rick_custom_action', 10, 3);
function marian_rick_custom_action ($result, $data, $format){
// get data from $data[] array
$email = $data['email'];
$key = $data['key'];
// use $data to create a personalized mail
$to = $email;
$subject = "Wordpress Test";
$content = "Hi, this us your key:" . $key . "Enjoy using it!";
// send mail using wp_mail
$status = wp_mail($to, $subject, $content);
}
if you are interested, how all this really works, check the official docs here

Email an image created on HTML5 canvas

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.

Categories