Get data from database and use in mail function in php - php

I am new to php and currently doing a project
I stored data in database by using a form.
I have a mail function, when on clicking the submit button, a mail is send to reputed email id. I am using phpmailer library.
This is my mail function
class mail
{
public function sendMail(){
require 'vendor/autoload.php';
$mail = new PHPMailer(); // Passing `true` enables exceptions or null without exception
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xyz#gmail.com'; // SMTP username
$mail->Password = 'xyz123'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('xyz#gmail.com', 'xyz');
$mail->addAddress('abc#gmail.com', 'abc');
$mail->addCC('zxc#gmail.com');
//Attachments
$mail->addAttachment('lob.png', 'sample.png'); // Add attachments
// Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Report';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
if (!$mail->send()) {
return "Error sending message" . $mail->ErrorInfo;
} else {
return "Message sent!";
}
}
}
This is my code to store data into database as send.php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$age = $_POST['age'];
$quality = $_POST['quality'];
$sql = "INSERT INTO user(name,age,quality) VALUES('$name','$age','$quality')";
}
This is my html form
<form class="quality" method="POST" action="send.php">
<label for="name">Name</label>
<input type = "text" class = "form-quality" name="name" value="" / >
<label for="age">Age</label>
<input type="text" class ="form-quality" name="age" value="" / >
<label for="quality">Quality</label>
<input type="ratio" class ="form-quality" name="quality" value="E" / >
<input type="ratio" class ="form-quality" name="quality" value="P" / >
</form>
1) How to get the data's from database ?
2) In mail function previously sending emails to one or two id's, but i need as when i select "value = E" from ratio button , it should send to one email and if i select "value= P" it should send to another email based on user selected values stored in the database
Anyone with a best reply will be much more needed help for me

Assuming that when you said you are doing a project is within an education environment and not for professional purpose:
When you get the data from you form on if(isset($_POST['submit'])) send those variables to the sendMail function as parameters, then inside the function you can make a variable using your parameters to build a well formed message that you can send in your $mail->Body .
Inside the function you can also check if what you recieved on your radio-button input was "E" or "P" and give different values (receivers email) and pass it to your addAddress.
If this is not a school project you MUST be very carefully on what you send or you insert to the db. Validate everything you recieve on your form before sending and go ahead and check the link in the comments about SQL injection.
This should've been a comment insetead of a reply but i don't have enough reputation to comment so sorry about that.

Related

PHP to send email with buttons that prompts answer from recipient and send back value to actual database

I would like to ask, how can i make the email i sent out to consist of two buttons which is accept or reject that when the recipient click on reject/accept, the value actually sends back to the database.
Does anyone have idea on this method ?
PHP
$subject1="E-Calibration Registration Form Approval Notice for HOD";
$message1="Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.";
$to1="67508#siswa.unimas.my";
//starting outlook
com_load_typelib("outlook.application");
if (!defined("olMailItem")) {define("olMailItem",0);}
$outlook_Obj1 = new COM("outlook.application") or die("Unable to start Outlook");
//just to check you are connected.
echo "<center>Loaded MS Outlook, version {$outlook_Obj1->Version}\n</center>";
$oMsg1 = $outlook_Obj1->CreateItem(olMailItem);
$oMsg1->Recipients->Add($to1);
$oMsg1->Subject=$subject1;
$oMsg1->Body=$message1;
$oMsg1->Save();
$oMsg1->Send();
echo "</br><center>Email has been sent succesfully</center>";
This is my php code for my email
The full solution consists of multiple parts:
Part 1: Send email script
I will use PHPMailer as an example. You should refer to the links for installation details.
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'user#example.com'; //SMTP username
$mail->Password = 'secret'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('sender#example.com', 'Sender');
$mail->addAddress('67508#siswa.unimas.my');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'E-Calibration Registration Form Approval Notice for HOD';
$id = 12345;
$body = '<p>Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.</p>';
$body.= '<p>Accept Reject</p>';
$mail->Body = $body;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Part 2: Response script
<?php
if(!isset($_GET['id'], $_GET['answer'])) {
die('missing parameters');
}
$id = (int)$_GET['id']; // assume ID is an integer
$answer = trim($_GET['answer']);
if(!in_array($answer, array('accept', 'reject'))) {
die('invalid answer');
}
// TODO: Save the info to MS Access DB
// read https://stackoverflow.com/questions/19807081/how-to-connect-php-with-microsoft-access-database for the codes
?>
So this functionality should start in the email you are sending. The email template or code should first of all be HTML to be able to accommodate the buttons. So the email mode should be HTML. These buttons can be linked to a form or direct links which denote Accept or Reject actions.
These can be the PHP file which then sends that information to the database.
<input type="submit" name="accept" value="Accept">
<input type="submit" name="accept" value="Reject">
Then in your PHP code, you can have your normal code to read these values and store them in the database.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$data = $_REQUEST['accept'];
// store in DB
}

Send MULTIPLE Attachments from Input on Form via PHPMailer

I have searched all around but cannot find a specific answer. I have a form there the user can put in MULTIPLE attachments. I am using PHPMailer to send the submitted form. I have looked everywhere and it seems people who explain how to upload multiple files but NOT from user input. THANK YOU!.
My attachment upload button name is "attachments"
if (isset($_POST["submit"])) {
$optionOne = $_POST['optionOne'] ;
$tick = $_REQUEST['tick'] ;
$results = $_REQUEST['results'] ;
$option = $_POST['option'] ;
$option = $_POST['requirements'] ;
$mail = new PHPMailer;
//Server settings
$path = 'upload/' . $_FILES["attachments"]["name"];
move_uploaded_file($_FILES["attachments"]["tmp_name"], $path);
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->isSendmail(); // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'bonnie'; // SMTP username
$mail->Password = 'bonnie'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('bonniethompson12345#gmail.com', 'Mailer');
$mail->addAddress('bonniethompson12345#gmail.com'); // Add a recipient
$mail->isHTML(true);
$mail->AddAttachment($path); // Set email format to HTML
$mail->Subject = 'Form submission';
$mail->Body = 'This course is identified in my Work Plan and Learning Agreement: $optionOne \n \n I am attending this session because: $tick \n \n What would you like to achieve as a result of your attendance: $results \n \n Do you require adjustments or additions to the session delivery to support your participation: $option \n \n Please provide details of your requirments: $requirements</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//$mail->AddAttachment('Logo.png');
if(!$mail->send()) {
echo "Failure to send";
} else {
echo "Message has been sent successfully";
}
}
<p>Please upload any supporting documentation to support your registration request </p>
<div class="browse-button">
<input type="file" name="attachments" multiple="multiple"></input>
</div>
The thing you're missing is the naming of the input element; you need to use array naming to make it handle multiple files correctly, so build it like this:
<input type="file" name="attachments[]" multiple="multiple">
The important bit is the [] at the end of the element name, which means that the multiple values will get submitted as an array. When you receive a submission from that, try a var_dump($_FILES) so you can see what you've got. You should also check the return value of move_uploaded_file() rather than assuming it works. Also you don't need a closing </input> tag if you're using HTML5.
The multiple file upload example provided with PHPMailer demonstrates exactly what you're asking, and includes the error checking I mentioned.
It's also covered in the PHP docs. Look harder next time!

Send php mail from html code [duplicate]

This question already has answers here:
How can I send an email using PHP?
(20 answers)
Closed 5 years ago.
after I tried to get an answer to my question here, I try it with a new thread.
Little explanation:
I have a Contact-Form with 180 input fields + calculation for every field.
I want to send all the fields + the calculated value with e-mail.
Thats just an example of one of the 180 rows which i need to send with mail:
<form id="wohnzimmer" method="post" action="mailto:myemail#mymail.com">
<div style="clear: left;">
<div class="text">
DIV TEXT - ANY ARTICLE
</div>
<div class="restText">
<input id="w0" type="text" class="raumeinheitInput_x4 inputWidth" value="0" name="ARTICLENAME" /> = <span class="raumeinheitenErgebnis" id="w0g"> CALCULATED NUMBER </span>
</div>
</div>
// 179 more input-fields will follow here!!
<input type="submit" value="Send Email" />
My Calculation is working, so i just need help to send all my content via mail.
My question is:
How can i send the mail without Outlook or Thunderbird (i think i need php)
with the following Content:
Name of the article , the Number from the Input field (w0) + the calculated number (w0g)?
I hope anyone has an answer for me.
Thanks in advance.
You need to create a PHP file to handle these "server-side" actions for you. Then set the action attribute of your HTML form to this PHP page. When the HTML is submitted, the 180 input fields are then all POSTed to the PHP page inside a variable called $_POST. You can then work on that data to create the string you want and finally use the mail() function (or perhaps a pre-built emailer package that gives you a bit more control) to actually send that email.
Your new HTML
<form id="wohnzimmer" method="post" action="send_email.php">
Note:
You say you want to get the name of the article, w0 and w0g, but you have only put w0 inside an input. Only inputs, textareas and selects will be sent to the PHP script. You will need to change your HTML to make sure they are all gathered. I'd suggest using array syntax to do this:
<input type="hidden" name="article0" value="ARTICLENAME" />
<input id="w0" type="text" class="raumeinheitInput_x4 inputWidth" value="0" name="w0" /> = <input type="text" class="raumeinheitenErgebnis" name="w0g" id="w0g"> CALCULATED NUMBER </input>
<input type="hidden" name="article1" value="ARTICLENAME" />
<input id="w1" type="text" class="raumeinheitInput_x4 inputWidth" value="0" name="w1" /> = <input type="text" class="raumeinheitenErgebnis" name="w1g" id="w1g"> CALCULATED NUMBER </input>
I'm making some presumptions here about your data but that should make sense. You may want to write a PHP loop to output the data if you can. Also it might help you to use HTML input arrays to simplify things a bit.
The PHP
You'd end up with something like this very rough example:
<?php
$myString = "";
for ($x=0;$x<180;$x++) {
$tempString = $_POST['article' . $x] . $_POST['w' . $x] . $_POST['w' . $x . 'g'];
// don't forget to sanitize this data!!
$myString .= sanitize_however_you_want($tempString);
}
// now email
mail('myemail#mymail.com', 'Email Subject', $myString, 'From: you#yoursite.com' '-fyou#yoursite.com');
Read more about posting forms here: Dealing with forms
Read more about sending email here: The mail() function
Read more about HTML input arrays in this stack question
you can use a mail() (http://php.net/manual/en/function.mail.php ) but i think is better if you use a PHPMailer library (https://github.com/PHPMailer) is
very simple
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}

inserting HTML POST form field data into PHPmailer email body

I have tried every hint I have found across the web and here but what I cannot achieve is for the sent email to contain the form data in the html formatted message. The mailing function is working and I get the email properly.
The form is basically:
<form method="post" action="test.php" name="Work Record" autocomplete="off">
<input type="text" name="first_name" id="staff_name2" placeholder="First" required />
<input type="text" name="last_name" id="staff_name" placeholder="Last" required />
<input name="checkbox" type="checkbox" class="head-l" id="checkbox" onChange="this.form.submit()">
And using the latest phpmailer from google the action script is as follows. I have the emailing function working through gmail, I am just not sure what to put where to pull the data from the form and put it into the email body. The code that is pasted in the body now is that we used to use before switching to phpmailer. Thank you!
<?php
require '/home/newnplhftp/nplh.us/smtp/phpmailer/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxxxxxxxxxxxxx'; // SMTP username
$mail->Password = 'xxxxxxxxx'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->From = 'xxxxxxxxxxxxxx';
$mail->FromName = 'NPLH';
$mail->AddAddress('xxxxxxxxxxxxxxxxxxxxx'); // Name is optional
$mail->AddCC('');
$mail->AddBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'xxxxxxxxxxxxxxx';
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
$mail->AltBody = '';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Thank you, your message has been sent!';
?>
Please set;
$mail->Body = '
<html>
<h2><b>$first_name $last_name, $license_type</b></h2>
</html>';
to
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
$mail->Body = "
<html>
<h2><b>".$first_name." ".$last_name.", ".$license_type."</b></h2>
</html>";
The variables you are trying to send need to be captured from the the form first. This would happen on test.php since this is where you are posting the values to.
So you would do this
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$license_type = $_POST['license_type'];
Then you can use them inside the mail body.
$mail->Body = "<html><h2><b>$first_name $last_name, $license_type</b></h2></html>";
Though I would highly suggest validating that data in some way first.

How to get user mails in my free gmail inbox through contact us form on my website

How to get user mails in my free gmail inbox through contact us form on my website. I do not use email with my website name . i use free gmail. I tried many script but the all need email account on domain.
Does this question have something to do with This One?
Well, so you have a form on your site, your users fill it up and you need an email with that data, right?
Simple example:
<form action="sendMail.php" method="post">
Name: <input type="text" name="name" id="name" /><br />
Email: <input type="text" name="email" id="email" /><br />
Text: <textarea name="text"></textarea><br />
<input type="submit" value="Send" />
</form>
then, the php page wich send the mail:
//php sendThis.php page
<?php
require("class.phpmailer.php");
$name = $_POST['name'];
$email = $_POST['email'];
$text = $name . ', ' . $email . ' has filled the form with the text:<br />' . $_POST['text'];
$from = 'your.email#gmail.com';
$to = 'your.email#gmail.com';
$gmailPass = 'your gmail password';
$mail = new PHPMailer();
$mail->IsSMTP();
// enable SMTP authentication
$mail->SMTPAuth = true;
// sets the prefix to the server
$mail->SMTPSecure = "ssl";
// sets GMAIL as the SMTP server
$mail->Host = 'smtp.gmail.com';
// set the SMTP port
$mail->Port = '465';
// GMAIL username
$mail->Username = $from;
// GMAIL password
$mail->Password = $gmailPass;
$mail->From = $from;
$mail->FromName = $from;
$mail->AddReplyTo($from, $from);
$mail->Subject = 'This is a test!';
$mail->Body = $text;
$mail->MsgHTML($text);
$mail->IsHTML(true);
$mail->AddAddress($to, $to);
if(!$mail->Send()){
echo $mail->ErrorInfo;
}else{
echo 'sent!';
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
EDIT: just tested and works fine. Make sure that the 3 files (class.phpmailer.php, class.pop3.php and class.smtp.php) are in the correct include path
Basically, it involves the PHP mail() function:
<?php
mail(yourGmailAddress, object, message);
?>
As you have already observed, this solution works only if the webserver operates a mail server. This mail server may forbid unknown users. So you need to have an email account on that web/mail server (I believe this is the case). The second step then is to forward mail from your website address to you gmail account. I am 90% certain that it is possible from your gmail configuration. It may also be possible from your website mail configuration. But don't configure both!
Try enabling openssl.
Uncomment the line:
extension=php_openssl.dll
in your php.ini file.
You can also put your email address into "action" attribute of the form element. But that's very unreliable. Like this:
<form method='post' action='mailto:your#email.com?Subject=Hello'>
...
</form>
Users must have email client installed and configured for this to work properly. There are some other drawbacks. You have to do some research to find whether this method is for you or not.
http://www.google.com/search?client=opera&rls=en&q=form+action+mailto&sourceid=opera&ie=utf-8&oe=utf-8

Categories