Send html form value to e-mail with php - javascript

I am stack with my form. I have to send value on e-mail. I don't know php, I know just JS(html, css). I have a very simple file structure, just html, css (a bit JS). I don't have any package manager.
I have to do my form with php.
-I found example, put php code on the top of my html file.
-Added .htaccess file
How I understand I need to use Apache as well, or not?
I don't have any idea about php - right me please some instruction what I have to do in simple way.

You can use PHPMailer to send emails easily. First you need to know how to get post data in PHP. and then store them as new variables then add them in Mail body to send.
Link for the PHPMailer: https://github.com/PHPMailer/PHPMailer
Tutorial for PHPMailer: https://github.com/PHPMailer/PHPMailer/wiki/Tutorial
You have to provide your email and password details in PHPMailer Library
Finally, Your PHP code be like below
<?php
require 'PHPMailerAutoload.php';
$name = $_POST['name'];
$email = $_POST['email'];
$mail = new PHPMailer;
$mail->setFrom('from#example.com', 'Your Name');
$mail->addAddress($email, 'My Friend');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = " Hi! $name This is my first e-mail sent through PHPMailer.';
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

Related

Not reloading website on form submission, yet send an email via php? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Submit form without page reloading
(19 answers)
Closed 5 years ago.
I have a contact form on my website. And I sent its contents to me via email via php:
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['firstname'];
$subject = "Form submission";
$message = $first_name . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
?>
This works. However, I don't want my page to be reloaded etc., so before I had the php code in there, I just coded the UI with javascript: It clears the fields, and it shows a notification saying Thanks for your message, etc. :
$("#contact_form").submit(function(e) {
e.preventDefault();
iziToast.success({
title: 'Thank you',
message: 'Thanks for your message',
});
this.reset(); //clear form input fields
});
HOWEVER:
The two don't seem to work together. I am doing prevent.default because I want to avoid a page reload, and I am doing a this.reset in order to reset the form and empty everything out again.
How could I make these two work together? That is, i want to send the email via php, but I also want to javascript to display the notification, clear the input fields, and not reload the page.
PS: The php is in the same file as the HTML. The javascript file is referenced via a script tag. Just in case that's important.

How to process HTML forms?

I have made an HTML form. It is a sort of a research form and generate scores based on the values entered through some formulae. After I have done with calculating scores, I want to send the scores via an email. Should I use PHP or JavaScript to do that?
thank you
PHP provides a convenient way to send email with the mail() function.
Syntax
mail(to,subject,message,headers,parameters)
Example :
<?php
$to = aa#bbb.com;
$subject = 'results';
$message = 'message ';
$headers = 'From: your_email#xxx.com';
mail($to, $subject, $message, $headers);
?>
You can learn this concept here
You can see examples here
Post your form to a PHP script and you can read the form fields using the $_POST variable. Make sure your form has name="xxx" fields. These will be your $_POST['xxx'] array index names.
You can do the calculations in Javascript,in browser, in clients side.
But sending emails.... you do this via PHP, on the server side.
An example of a PHP script sending the email, as follows
See how I get form field values using $_POST array they come in?
You can build a looong email using lots of variables, just add them to the message.
<?php
$to = $_POST['email'];
$subject = 'Your results';
$message = 'Hello, this is your score email.<br>';
$message.= 'Your result is: '.$_POST['score'];
$headers = 'From: your#email.com';
mail($to, $subject, $message, $headers);

allow only emails from specific domain/subdomain to register and send verification email [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Can someone show me how to allow only emails from specific domain/subdomain to submit email in a form. After submission I would like the email to be sent both to the user's email and my own email. I'm not really sure how to integrate it, so that's mostly what I need help with.
To set up a form that will only accept email addresses with certain domains, you can do two things.
The first is to use the HTML5 input type="email" attribute, which can be used to make sure that any browser that supports HTML5 can validate the email to at least be a valid one.
HTML file:
<form id="contact-form">
<!-- Other inputs here -->
<input name="user-email" type="email" id="user-email" placeholder="johnny.appleseed#gmail.com" required>
<!-- make sure this name="" attribute matches what you ask for in the PHP -->
<button type="submit" id="form-submit">Submit!</button>
</form>
Then you can also use JavaScript to check the domain. Once you know that the email is valid and fits your constraints, you will need to set up an AJAX POST that will send data to the server to handle sending the email. This part can be done like so:
JavaScript file:
$('#form-submit').on('click', function(e) {
e.preventDefault(); // prevent the button from refreshing the page
var userEmail = $('#user-email');
if (userEmail.val().indexOf('.com') !== -1) { // validation
// xyz has .com in it
} else if (userEmail.val().indexOf('.org') !== -1) { // validation
// xyz has .org in it
} else {
$('#submission-info').text('Whoops, we don't send emails, to anything other than .org or .com, please enter a different email and try again.');
}
// this doesn't mean .com or .org is at the end
// you may want to check that by using a regular expression if necessary
var formData = $('#contact-form').serialize(); // This gets the <form id="contact-form"> element's values and serializes it into a string.
$.ajax({
url: 'mail.php', // make sure this file is either in the same directory or the path is changed
type: 'POST',
data: formData
}).done(function(response) {
// do stuff to to show the user that the form was submitted
$('#submission-info').text('Success, your information has been sent to us (and the NSA of course) and we will reply to you as soon as possible.');
}).fail(function(response, error) {
// tell the user what happened that caused the form submission to fail
$('#submission-info').text('Oh no, something happened. Maybe try again');
});
});
For more info about serializing, check out jQuery's API page.
Then in mail.php, you can handle it in PHP by doing something like this:
<?php
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$formcontent = "From: $firstname $lastname \n Email address: $email \n Message: $message";
$recipient = "john.doe#gmail.com"; // your email goes here instead
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>
If you use something like PHPMailer, then you can do all kinds of stuff and it is somewhat more intuitive and clearer and offers many more options that you can configure.
Using PHPMailer would look something like this for a mail.php file:
<?php
require_once("class.phpmailer.php"); // this path should also be set up properly
if ($_POST) { // If something was sent by submitting the form.
$name = htmlspecialchars($_POST["user-name"]);
$email = htmlspecialchars($_POST["user-email"]);
$message = htmlspecialchars($_POST["comment"]);
$subject = "Contact form";
$to = "john.doe#gmail.com"; // your email here
$userBcc = $_POST["user-bcc"]; // You can BCC the user's email
$mail = new PHPMailer();
$mail->From = "xyz#xyzs.com"; // make sure to change this to something else
$mail->FromName = "XYZ XYZ"; // change this too.
$mail->AddReplyTo($email, $name);
if($userBcc == true) {
$mail->addBCC($email);
}
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->Send()) {
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
?>
So now you should have a form that works. I would suggest testing it a little bit by just sending emails to yourself and doing test submissions before you make it live. You may also want to implement some form of anti-spam, depending on the audience using the site. Forgive me if I forget anything or it isn't clear, I will edit the post and try to detail/fix anything I can.
Good luck and let me know how it goes!

Sending an uploaded file through email without saving it first

I am creating an application that allows a user to attach a file, type a message, then an email is sent using the PHP mailer plugin for wordpress. I use javascript to get the file information from the upload html form and then php to send the email. The plugin works when sending a file that is saved on the server in a specific location using this function:
$mail->AddAttachment("./new6.txt","attachment");
I was wondering if there is a way to email the file selected without having to save it to the server. In other words, can a user select a file to upload, but send the file with this php function without saving it in a location to be retrieved? I know there is a $_FILES array that you can get the file's information but will that file be able to be sent without it being saved somewhere first? I'm guessing not since the whole point of the upload form is to "upload" it but just wondering if something could be done in javascript or something.
Thanks for any help
You can't truly do that, but you could do this to get a close effect:
$filename = $_FILES['file_name']['tmp_name'];
$main->AddAttachment($filename, "attachment");
// Send the email... then:
unset($filename);
This adds the file as an attachment, sends the email, then deletes the file. The uploaded files in the $_FILES array will automatically be flushed out eventually, so I'm not sure if the unset() part even does anything significant, but it surely gets rid of the file.
Without Saving file in Server, you can not attach it for mail.
1> Mailing function is executing in Server.
2> It is not possible from Server to get the absolute file path in client machine as in web, the client machines do not have any absolute address.
3> So the file is needed to be uploaded in server to get a real path for the file to have in attachment of Mail.
I know this is a rather old question, but I think there's a rather useful answer that was never given. For the sake of those like me who happned along this question while searching for an answer to this question or similar, here you go.
When you upload a file to a server from a form, it's saved to the tmp directory automatically. Technically it's impossible to do anything with a form uploaded file without saving, because it's done for you automatically. However, because tmp is automatically cleaned on every reboot, this shouldn't be an issue in terms of building up too much backlog, if you either reboot often or set up a cron to delete your tmp directories contents regularly.
However, because it's saved to tmp, and because you can manipulate the file from there, it is possible to send the file without saving it for any form of longevity, and without actually writting anything to save it. Provided you perform all the necessary security checks on the file (verifying the contents, MIME-type and such that I won't go into now, but you can read up on how to do here), you can use the following php function which I got from Codexworld and modified to use the tmp files. All you need to do is pass
the parameters, and the $files is an array of files you've hopefully already vetted.
function multi_attach_mail($to, $subject, $message, $senderEmail, $senderName, $files = array()){
$from = $senderName." <".$senderEmail.">";
$headers = "From: $from";
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// Preparing attachment
if(!empty($files)){
for($i=0; $i<count($files); $i++){
if(is_file($files[$i]["tmp_name"])){
$tmp_name = basename($files[$i]["tmp_name"]);
$file_name = $files[$i]["name"];
$file_size = filesize($files[$i]["tmp_name"]);
$message .= "--{$mime_boundary}\n";
$fp = fopen($files[$i]["tmp_name"], "rb");
$data = fread($fp, $file_size);
fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$file_name."\"\n" .
"Content-Description: ".$file_name."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".$file_name."\"; size=".$file_size.";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderEmail;
// Send email
$mail = mail($to, $subject, $message, $headers, $returnpath);
// Return true, if email sent, otherwise return false
if($mail){
return true;
}else{
return false;
}
}

E-mail a value which is returned by a function

I was wondering if it is possible to email a value which is returned by a function in javascript? or do i have to use php/ajax?
From the following example, I want to email abc to myself? How can it be done?
<html>
<head><script>
var t = "abc";
function test(){
return t;}
</script></head>
<body onload = "test()">
</body></html>
You'll need to post it to your server via XHR, then your server can email it.
Here is a very good explanation from another similar question:
You can't send an email with javascript,
the closest you can get
would be a mailto which opens the
default email client - but that won't
send anything.
Email should be sent from the server -
submit the form in the normal way, and
construct the email on the server and
send it....
Another answer there gives some details about using mailto.
There's no direct method. I would use jQuery' $.post to post the relevant information to a PHP page which would then mail it using, at it's simplest, the aptly-named mail function.
In one of the script tags of the main page or in a separate .js file:
$.post("mailer.php", {data: "abc"}, function(data) {
// Alert yourself whether it was successful if you want
});
And mailer.php (replace these with your own values):
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = $_POST['data'];
$headers = 'From: webmaster#example.com';
mail($to, $subject, $message, $headers);
?>

Categories

Resources