I have a simple contact form. It sends email via AJAX. Works fine.
Now I need to create PDF file from results of this form and download it to user like here
So html form:
<form id="contact-form">
<input type="hidden" name="action" value="contact_send" />
<input type="text" name="name" placeholder="Your name..." />
<input type="email" name="email" placeholder="Your email..." />
<textarea name="message" placeholder="Your message..."></textarea>
<input type="submit" value="Send Message" />
</form>
In functions.php I have function to send email:
function sendContactFormToSiteAdmin () {
try {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
}
if (!is_email($_POST['email'])) {
throw new Exception('Email address not formatted correctly.');
}
$subject = 'Contact Form: '.$reason.' - '.$_POST['name'];
$headers = 'From: My Blog Contact Form <contact#myblog.com>';
$send_to = "contact#myblog.com";
$subject = "MyBlog Contact Form ($reason): ".$_POST['name'];
$message = "Message from ".$_POST['name'].": \n\n ". $_POST['message'] . " \n\n Reply to: " . $_POST['email'];
if (wp_mail($send_to, $subject, $message, $headers)) {
echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
exit;
} else {
throw new Exception('Failed to send email. Check AJAX handler.');
}
} catch (Exception $e) {
echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
exit;
}
}
add_action("wp_ajax_contact_send", "sendContactFormToSiteAdmin");
add_action("wp_ajax_nopriv_contact_send", "sendContactFormToSiteAdmin");
So in footer.php i have a script ajax handler:
jQuery(document).ready(function ($) {
$('#contact-form').submit(function (e) {
e.preventDefault(); // Prevent the default form submit
var $this = $(this); // Cache this
$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
type: 'post',
dataType: 'JSON', // Set this so we don't need to decode the response...
data: $this.serialize(), // One-liner form data prep...
beforeSend: function () {},
error: handleFormError,
success: function (data) {
if (data.status === 'success') {
handleFormSuccess();
} else {
handleFormError(); // If we don't get the expected response, it's an error...
}
}
});
});
});
All of it works great. But i don't understand where i have to paste code for creation PDF, i have tried to paste it in sendContactFormToSiteAdmin php function, but it didn't work.
As in this example i need to paste this code exactly in sendContactFormToSiteAdmin php function:
ob_start();
?>
<h1>Data from form</h1>
<p>Name: <?php echo $name;?></p>
<p>Email: <?php echo $email;?></p>
<?php
$body = ob_get_clean();
$body = iconv("UTF-8","UTF-8//IGNORE",$body);
include("mpdf/mpdf.php");
$mpdf=new \mPDF('c','A4','','' , 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($body);
$mpdf->Output('demo.pdf','D');
But i don't understand how to do this with ajax response.
Edit
As Shoaib Zafar commented, if it is possible to email pdf file as an attachment to email, of course for me it is the best.
To email the PDF as an attachment, you need to alter your email sending function.
function sendContactFormToSiteAdmin () {
try {
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
}
if (!is_email($_POST['email'])) {
throw new Exception('Email address not formatted correctly.');
}
ob_start();
?>
<h1>Data from form</h1>
<p>Name: <?php echo $_POST['name'];?></p>
<p>Email: <?php echo $_POST['email'];?></p>
<?php
$body = ob_get_clean();
// Supposing you have already included ("mpdf/mpdf.php");
$mpdf=new \mPDF('c','A4','','' , 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($body);
$pdf_content = $mpdf->Output('', 'S');
$pdf_content = chunk_split(base64_encode($pdf_content));
$uid = md5(uniqid(time()));
$filename = 'contact.pdf';
$subject = 'Contact Form: '.$reason.' - '.$_POST['name'];
$message = "Message from ".$_POST['name'].": \n\n ". $_POST['message'] . " \n\n Reply to: " . $_POST['email'];
$header = 'From: My Blog Contact Form <contact#myblog.com>';
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $pdf_content."\r\n\r\n";
$header .= "--".$uid."--";
$send_to = "contact#myblog.com";
$subject = "MyBlog Contact Form ($reason): ".$_POST['name'];
if (wp_mail($send_to, $subject, $message, $header)) {
echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
exit;
} else {
throw new Exception('Failed to send email. Check AJAX handler.');
}
} catch (Exception $e) {
echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
exit;
}
}
I don't know much about how wp_email function work but technically this code should work, you only need to refactor it.
And you can also find this in the official documentation to learn more about it mPDF Example #3
Related
Not really familiar with PHP but I need to use it to submit a form.
However, I want it to navigate to a page after form submission.
Here's my code:
<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
Right now, submitting the form takes me to a new page which just shows the $okMessage text
<form id="form" class="topBefore" method="post" role="form" action="contact.php">
<input id="name" name="name" type="text" placeholder="NAME">
<input id="email" name="email" type="text" placeholder="E-MAIL">
<input id="submit" type="submit" value="Send">
Use php header('Location: somepage.php');
if(mail($sendTo, $subject, $emailText, "From: " . $from))
{
header('Location: somepage.php');
}
Note: The php mail() function will return true if the message is accepted for delivery but doesn't guarantee that it will be delivered.
Edit: have a look at my simple email function with try catch statement. Compare with your answer maybe it will help you.
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
//post varables from your form
//$name = $_POST['name'];
$name = 'John';
//$email = $_POST['email'];
$email = 'johndoe#blah.com';
//Email header
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html;charset=iso-8859-1" . "\r\n";
$header .= "From: $from" . "\r\n";
$header .= "Reply-To: ..." . "\r\n";
$emailText = "You have new message from contact form <br/> ============================ <br/> Name : $name <br/> Email : $email <br/>";
try
{
if (mail('demo#domain.com', $subject, $emailText, $header))
{
header('Location: somepage.php');
}
else
{
throw new Exception($errorMessage);
}
}
catch (Exception $ex)
{
echo 'Message: ' . $ex->getMessage();
}
I am making a php form in wordpress.I would like to attach a notepad or PDF file along this form.I am getting all this in email using mail function in a body variable for example
$body =" Attachment: $Attachmentfile";
Instead of file i am receiving file name that user uploading instead of file.I am trying to receive file in email.Actually i am learning too that how to do it.
My php code for assigning to htm file tag is,
if(trim($_POST['Attachmentfile']) === '') {
$AttachmentfileError = 'Please enter a Pdf, Notepad or Word file.';
$hasError = true;
}
else
{
if($_FILES["Attachmentfile"]["name"] != "")
{
$strFilesName = $_FILES["Attachmentfile"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["Attachmentfile"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
else
{
$Attachmentfile = trim($_POST['Attachmentfile']);
}
}
and my Html code for getting file ,
<li class="left">
<label for="CV">Attachments :</label><span class="error">*</span><br>
<input class="txt" type="file" name="Attachmentfile" id="Attachmentfile" value="<?php if(isset($_POST['Attachmentfile'])) echo $_POST['Attachmentfile'];?>">
</li>
and this is my mail function code,
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$headers .= "\r\n" . 'Content-type: text/html';
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
Can you help and modify my code in order to get file in email.Thanks friends.
function property_add() {
$data = $_POST['data'];
$data = array_map('trim',$data);
extract($data);
$to = "reciever mail here ";
$subject = "subject here";
$message ='Message here';
$attachments = array(); // initialize attachment array
$upload_dir = wp_upload_dir(); // look for this function in wordpress documentation at codex
$upload_dir = $upload_dir['path'];
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["images"]["tmp_name"][$key]; // Get temp name of uploaded file
$name = time().'_'.$_FILES["images"]["name"][$key]; // rename it to whatever
move_uploaded_file($tmp_name, "$upload_dir/$name"); // move file to new location
$attachments[] = "$upload_dir/$name"; // push the new uploaded file in attachment array
}
}
add_filter( 'wp_mail_content_type', 'set_html_content_type' ); // allow html tags in mail
if(wp_mail($to, $subject, $message,'',$attachments)) {
echo "any success message>";
} else {
echo "failure message ";
}
remove_filter( 'wp_mail_content_type', 'set_html_content_type' ); // remove filter to avoid conflicts
if(!empty($attachments)) {
foreach($attachments as $attachment) {
#unlink($attachment); // delete files after sending them
}
}
}
this is an extract of one of my project .. change it according to your needs i wrote comment so that you get better better ..
call this function on form submit
I have a problem of using the jquery to send the base64_image to my form and echo it on that page for customers to preview. as that form is for customers to fill in their information and double check the image, once they have confirmed, the data they fill in will send to my email address. However, the image cannot shown in the preview section and in email as well.
For the base64_image, is customers using the jquery to create their design picture. Please find below code for your ref.
index.php
$('#send-button').click(function(){
fpd.createImage(true, true);
return false;
});
//the handler when the image is created
$('#fpd').bind('imageCreate', function(evt, canvas, base64Image) {
//send 64-bit encoded image url to php
$.post("php/form.php", { base64_image: base64Image }, function(data) {
//successful
if(data) {
//open product image a new window
console.log('Mail successfully sent!');
}
//failed
else {
console.log('Mail could not be sent');
}
} );
});
send
form.php
<form name= "myForm" form action="send.php" method="post" onsubmit="return validateForm()">
<td align="right" valign="middle" class="text">Picture Preview:<img src="<?=$base64_str;?>"></img></td>
</form>
send.php
$base64_str = substr($_POST['base64_image'], strpos($_POST['base64_image'], ",")+1);
$to = 'xxx#gmail.com';//set here your receiving mail address
$subject = 'test'; //set here the mail subject
$bound_text = md5(date('r', time()));
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";
$headers = "From: xxx#yahoo.com.hk\r\n";//set here the sending mail address
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"$bound_text\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
.$bound;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."Your message goes here\r\n" //set here the mail text
.$bound;
$message .= "Content-Type: image/png; name=\"mail_product.png\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-disposition: attachment; file=\"mail_product.png\"\r\n"
."\r\n"
.chunk_split($base64_str)
.$bound_last;
if(mail($to, $subject, $message, $headers))
{
echo json_encode(1);
} else {
echo json_encode(0);
}
?>
Whats the problem? Sending the email or show the preview, or both?
Do the jQuery script sent the data to the php file correctly? Have you debug this?
What is the returning value in (data)? Do you get 0, 1 or something else?
Do you have set up your own smtp mail server or using gmail`s smtp server?
I tried earlier with no solution, so I'm adding all my code to try and resolve this issue. I am not getting this form in my inbox, but my ajax function is working like it should. I have godaddy hosting, and am running it locally on wampp for mac. I've tried multiple different email addresses with no avail. I don't want to use php mailer. I just want this to function properly instead of what it seems to be doing which is shooting emails into outter space
html
<div class="block">
<div class="done">
<h1>Thank you! I have received your message.</h1>
</div>
<div class="form">
<form method="post" action="scripts/process.php">
<input name="name" class="text" placeholder="Name" type="text" />
<input name="email" class="text" placeholder="Email" type="text" />
<textarea name="comment" class="text textarea" placeholder="Comment"></textarea>
<input name="submit" value="Let's Go!" id="submit" type="submit" />
<div class="loading"></div>
</form></div>
</div>
<div class="clear"></div>
</div>
</div>
jquery validation and ajax
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var comment = $('textarea[name=comment]');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailVal = email.val();
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (!emailReg.test(emailVal)){
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (name.val()=='') {
name.addClass('hightlight');
}else{name.removeClass('hightlight');}
if (email.val()=='') {
email.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (comment.val()=='') {
comment.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (name.val()=='' || email.val()=='' || comment.val()=='') {
return false;
}
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "scripts/process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
and the php which I regret to say I know very little about for now
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course,
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'myemail#gmail.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Comment from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name</td><td>' . $name . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! Matt has received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
There are so many issues on sending PHP mails to different mail servers. For example, when I want to send email to GMail hosts I never include \r for new lines and I only go with \n. Maybe your problem is with your headers, I place my code here and see what you can get:
function send($address, $subject, $content, $from = '', $html = FALSE, $encoding = 'utf-8')
{
if(empty($address) || empty($content)) return;
$headers = "";
if($from != '')
{
$headers .= "From: {$from}\n";
$headers .= "Reply-To: {$from}\n";
}
$headers .= "To: {$address}\n";
if($html)
{
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset={$encoding}\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
}
$headers .= "X-Priority: 1 (Highest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";
$headers .= "X-Mailer: PHP/" . phpversion();
set_time_limit(30);
mail($address, $subject, $content, $headers);
}
send('myemail#myhost.com', 'title', 'content', 'myemail <myemail#myhost.com>', FALSE);
Alright, I'm starting to pull my hair and I need some help :)
Here is my file which is used to select activated emails from users and send them some sort of newsletter.
Content of the newsletter.php
<?php
//Include configuration file
include 'config/config.php';
$pdo = new PDO("mysql:host=localhost;dbname=$db", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Define messages
//Error messages
define('ERROR_MESSAGE_SUBJECT', 'Enter subject');
define('ERROR_MESSAGE_CONTENT', 'Enter some content');
//Define variables
$errorFlag = false;
$to = array();
//Grab variables
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$newsletterSubject = check_input($_POST['newsletterSubject']);
$newsletterContent = $_POST['newsletterContent'];
if(!$newsletterSubject) {
$errorSubject = ERROR_MESSAGE_SUBJECT;
$errorFlag = true;
}
if(!$newsletterContent) {
$errorContent = ERROR_MESSAGE_CONTENT;
$errorFlag = true;
}
}
?>
<form action="newsletter.php" method="post">
<label>Naslov newsletter-a: <?php echo '<span class="error">'.$errorSubject.'</span>';?></label>
<input type="text" class="linput rounded" name="newsletterSubject">
<label>Sadržaj newsletter-a: <?php echo '<span class="error">'.$errorContent.'</span>';?></label>
<textarea name="newsletterContent" class="rounded"></textarea><br>
<input type="submit" class="submit button rounded" name="newsletterSend" value="Pošalji newsletter korisnicima">
</form>
<?php
if (!$errorFlag) {
echo '
<div class="heading">
<h1>Sending statistic</h1>
</div>';
$query = $pdo->prepare('SELECT email FROM users WHERE active=:active');
$query->bindValue(':active', '1');
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
$i=1;
while($row = $query->fetch()) {
$to[] = $row['email'];
}
print_r($to);
if(!empty($to)) {
foreach($to as $mail) {
$headers = "From: " . $fromEmail . "\r\n";
$headers .= "Reply-To: ". $fromEmail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= $newsletterContent;
$message .= '</body></html>';
mail($mail, $newsletterSubject, $message, $headers);
$i++;
}
}
}
?>
After selecting active emails from database, array $to contains:
Array ( [0] => somemail1#domain.com [1] => somemail2#domain.com )
And that is correct, but both emails will receive 2 emails, so 4 in total. Normally one email should receive one newsletter.
And there is also something else strange, when first newsletter is received, it contains subject and message. However second newsletter doesnt contain anything except 'to' field.
So to sum up, this file sends two emails per one email in database.
I tried to create test file with same array and this is content of it:
test.php
<?php
$fromEmail = 'from#mydomain.com';
$to = array('somemail1#domain.com', 'somemail2#domain.com');
print_r($to);
foreach($to as $mail) {
$headers = "From: " . $fromEmail . "\r\n";
$headers .= "Reply-To: ". $fromEmail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= $newsletterContent;
$message .= '</body></html>';
mail($mail, $newsletterSubject, $message, $headers);
$i++;
}
?>
This test file sends normal email - one email per one email. So server configuration should be okay.
It looks like it's because your send code isn't inside the code block which checks that it is POST, so it sends once when you load the page and again when you fill in the form and submit it.
Move the whole if (!$errorFlag) block into the if ($_SERVER['REQUEST_METHOD'] == 'POST') block.