This is my site --> nodeiterator.pl
Why when I send email WITHOUT $mail->addAttachment($file); I DO receive email but... when I add $mail->addAttachment($file); I DO NOT receive email on my mailbox even though I receive sussess message...What Am I missing here? My aim is to send form result to my mail box WITH attachement file...
Below This is my PHP script responsible for sending message:
<?php
$msg = "";
use PHPMailer\PHPMailer\PHPMailer;
include_once "phpmailer/PHPMailer.php";
include_once "phpmailer/Exception.php";
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$nazwisko = $_POST['nazwisko'];
$imie = $_POST['imie'];
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
$file = "attachment/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
$file = "";
$mail = new PHPMailer();
$message = "
<html>
<head>
<meta charset=\"utf-8\">
</head>
<style type='text/css'>
body {font-family:sans-serif; color:#222; padding:20px;}
div {margin-bottom:10px;}
.msg-title {margin-top:30px;}
table {
border-collapse:collapse;
}
</style>
<body>
<table border=\"2\">
<tr>
<td>Nazwisko osoby ubezpiecząjacej :</td>
<td>$nazwisko</td>
</tr>
</table>
</body>
</html>";
$mail->addAddress('piterdeja#gmail.com');
$mail->setFrom($email);
$mail->isHTML(true);
$mail->Body = $message;
$mail->addAttachment($file);
$mail->AllowEmpty = true;
if ($mail->send())
$msg = "Your email has been sent, thank you!";
else
$msg = "Please try again!";
unlink($file);
}
?>
Related
on my page when the user submits a form it sends details to my email and went to a new URL.
after the user went t the new URL I want there to show the user about that form that your form is submitted in a toast notification
PHP script for form send via email is this
<?php
if (isset($_POST["sendmessage"])) {
$fname = $_POST["fullname"];
$fnumber = $_POST["phonenumber"];
$femail = $_POST["fullemail"];
$fsubject = $_POST["fullsubject"];
$fmessage = $_POST["fullmessage"];
$status = "";
$subject = "Contact Form | MAKT Website";
$body =
'<p style="font-size: 18px;">New Message has been submitted from your website contact form</p><br>';
$body =
"<br> Below Are the details for the query <br> <b>Name: </b> " .
"<br> <b>Full Name: </b>\n $fname" .
"<br> <b>Phone: </b>: $fnumber" .
"<br> <b>Email: </b> $femail" .
"<br> <b>Subject: </b> $fsubject" .
"<br> <b>Customer Message: </b> $fmessage";
$email_to = "m.ahmed4821#l.com";
$email_from = "no-reply#mrmakt.com"; // Enter Sender Email
$sender_name = "M.A.K.T- Website"; // Enter Sender Name
require "PHPMailer/PHPMailerAutoload.php";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mrmakt.com"; // Enter Your Host/Server
$mail->SMTPAuth = true;
$mail->Username = "no-reply#mrmakt.com"; // Enter Sender Email
$mail->Password = "";
//If SMTP requires TLS encryption then remove comment from it
//$mail->SMTPSecure = "tls";
$mail->Port = 26;
$mail->IsHTML(true);
$mail->From = $email_from;
$mail->FromName = $sender_name;
$mail->Sender = $email_from; // indicates ReturnPath header
$mail->AddReplyTo($email_from, "No Reply"); // indicates ReplyTo headers
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($email_to);
if (!$mail->Send()) {
$status = "Mailer Error: " . $mail->ErrorInfo;
} else {
?>
<script>
location.replace("index.php?message=your-message-has-been-sent")
</script>
<?php
}
} else {
$msg = "Something Went Wrong. Please try again";
}
?>
after sending the form to new URL I am getting the value using this below ode and trying to display the toast also using the below code
<?php
if (isset($_GET["message"])) {
$querysubmitted = "Thank You....! Your Message has been sent|.";
}
?>
<?php if ($querysubmitted) { ?>
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<img src="imgs/MAKT_FALCON_PMG.png" class="rounded me-2" alt="MAKT_LOGO">
<strong class="me-auto">M.A.K.T</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
<?php echo htmlentities($querysubmitted); ?>
</div>
</div>
<?php } ?>
Please help me with that
thanks in advance
I want to use the below contact us form; I tested it, and I sent emails. There are few issues that I am unable to sort out so that I use the form on a development site. The issues are:
When the user hits send an email button while the form is empty, he does not get an alert that the ReCaptcha field is required.
If you fill the form and completely ignore the ReCaptcha and hit the send button, you will be taken to a white page, and the email will not be sent. Obviously, this is an error that is not communicated properly to the user.
If you fill the form properly and hit send, the thank you page's code does not capture your message. I tried using both GET and Post. For example: <?php echo $_POST["name"]?> and <?php echo $_GET["name"]?>.
I use PHP version 8.0.3.
I appreciate it if someone can help me solve these issues.
Index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Test form to email</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class ="container">
<div class="col-lg-6 push-lg-3">
<h1> Contact us</h1>
<p>Fill out the below form to contact us</p>
<form id= "contactus" method= "post" action= "send.php">
<input type= "text" name = "name" class = "form-control" placeholder="your Name" required><br />
<input type= "tel" name = "phone" class = "form-control" placeholder="your Phone" required><br />
<input type= "email" name = "email" class = "form-control" placeholder="your email address" required><br />
<textarea name="message" placeholder="your Message" class = "form-control" required></textarea><br />
<div class="g-recaptcha" data-sitekey="ENTER_YOUR_SITE_KEY_HERE"></div><br />
<button type= "submit" class = "btn btn-success">Send email</button>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src="./js/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
$("#contactus").validate();
</script>
</body>
</html>
send.php
<?php
/**
* Contact us form for PHPMailer and ReCaptcha V2.
* Built based on the following resources
* https://www.youtube.com/watch?v=3o0WXaXfUwI
* https://stackoverflow.com/questions/50253428/verify-recaptcha-v2-always-false
* This code is not yet final and requires refinement and help from the great community of stackoverflow.com
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php'; //confirm this path
require 'vendor/phpmailer/phpmailer/src/SMTP.php'; //confirm this path
require 'vendor/phpmailer/phpmailer/src/Exception.php'; //confirm this path
//get the variables from the form
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
//validations
if(empty($name)){
header("location:index.php?nouser");
exit();
}
if(empty($phone)){
header("location:index.php?nophone");
exit();
}
if(empty($email)){
header("location:index.php?noemail");
exit();
}
if(empty($message)){
header("location:index.php?nomessage");
exit();
}
//PHPMailer desfault validations
//Apply some basic validation and filtering to the email
if (array_key_exists('email', $_POST)) {
$email = substr(strip_tags($_POST['email']), 0, 255);
} else {
$email = 'No email';
}
//Apply some basic validation and filtering to the message
if (array_key_exists('message', $_POST)) {
//Limit length and strip HTML tags
$message = substr(strip_tags($_POST['message']), 0, 16384);
} else {
$message = '';
$msg = 'No message provided!';
$err = true;
}
//Apply some basic validation and filtering to the name
if (array_key_exists('name', $_POST)) {
//Limit length and strip HTML tags
$name = substr(strip_tags($_POST['name']), 0, 255);
} else {
$name = '';
}
//Load Composer's autoloader
require 'vendor/autoload.php'; //confirm this path
$response = isset($_POST["g-recaptcha-response"]) ? $_POST['g-recaptcha-response'] : null;
$privatekey = "ENTER_YOUR_PRIVATE_KEY"; //Enter your secret key here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $privatekey,
'response' => $response,
'remoteip' => $_SERVER['REMOTE_ADDR']
));
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'mail.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'support#example.com'; //SMTP username
$mail->Password = 'PASSWORD'; //SMTP password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Sender
$mail->setFrom('sender#example.com', 'Mr.sender');
//Recipients
$mail->addAddress('recipient#example.com', 'Mr. Recipient'); //Add a recipient
//Body content
$body = "<p><strong>Hello</strong>, you have received an inquiry from " . $name . " the message is " . $message . " you can contact the sender by phone on " . $phone . " or by email on " . $email . "</p>";
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Website inquiry from ' . $name;
$mail->email = 'The sender email ' . $email;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
//echo 'Message has been sent'; // select this if you want to echo that the message has been snet
header("location: thankyou.php"); // Select this if you want to redirect to a thank you page
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>
thankyou.php
<!DOCTYPE HTML>
<html>
<head>
<title>Thank you <?php echo $_GET['name'];?> </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container mt-5 text-center">
<body>
<h1>Thank You <?php echo $_GET['name'];?></h1>
<p>We have received your inquiry. Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_GET["name"]?></li>
<li><em>Email:</em> <?php echo $_GET["email"]?></li>
<li><em>Phone:</em> <?php echo $_GET["phone"]?></li>
<li><em>Message:</em> <?php echo $_GET["message"]?></li>
</ol>
</body>
</div>
</body>
</html>
i have created finally this code for a contact form and there is one thing missing as i want to but maximum size 5 MB and when if tried function if($file_size > 5000000){$fileErr = "max allowed size is 5 mb";} else{$check6 = 1;} but it didn't work and the code is not working but if i remove this function everything else will work great so any help with that and when i solve this problem i will add the code here so everyone can get a benefit from that .... and here is the code below
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<!-- Start PHP CODE -->
<?php
// Show errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $fileErr = $fileErr2 = $result = "" ;
// when we press submit do the following
if(isset($_POST['submit']))
{
// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Checks variables
$check1 = $check2 = $check3 = $check4 = $check5 = $check6 = "";
// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
$fnameErr = "Name is Required";
}else{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}else{
$check1 = 1;
}
}
// Checking the Last Name
if(empty($_POST["lname"])){
$lnameErr = "Name is Required";
}else{
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}else{
$check2 = 1;
}
}
//Checking the Email Adress
if(empty($_POST["email"])){
$emailErr = "Email is Required";
}else{
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}else{
$check3 = 1;
}
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
$humanErr = "Please Enter the Answer";
}else{
if ($human != 4){
$humanErr = "Please check your answer";
}else{
$check4 = 1;
}
}
// checking the attachment
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
$fileErr = "File $file_name has the extensions $ext which is not allowed";
}else{
$check5 = 1;
}
if($file_size > 5000000){
$fileErr = "Max allowed size is 5 MB";
} else {
$check6 = 1;
}
array_push($files,$file);
}
// define email variables
$to = 'eng.bolaraafat#gmail.com';
$from = "qyas.ae- contact form";
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
'E-mail: '.$email."\r\n".
'Telephone: '.$tel."\r\n".
'Designation: '.$design."\r\n".
'Country Appled From: '.$country."\r\n".
'Message: '.$comment."\r\n"."\r\n";
$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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
if(!empty($_FILES["my_file"])){
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}}else{
$fileErr = "Please Attach your Resume";
}
// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 && $check5 && $check6 == 1){
mail($to, $subject, $message, $headers);
$result = "Message Sent Sucessfully";
}else{
$result = "Message Can't be sent";
}
} }
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!-- END OF PHP CODE -->
<h2>Contact Form</h2>
<p><span style="color: red" >*Required fields</span></p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
First Name:<input type="text" name="fname"><span style="color: red" >* <?php echo $fnameErr ?> </span><br><br>
Last Name:<input type="text" name="lname"><span style="color: red" >* <?php echo $lnameErr ?></span> <br><br>
E-mail:<input type="text" name="email"><span style="color: red" >* <?php echo $emailErr ?></span> <br><br>
Telephone:<input type="text" name="tel"><br><br>
Designation:<select name="design">
<option value="Architectural Engineer">Architectural Engineer</option>
<option value="Structural Engineer">Structural Engineer</option>
<option value="Draughts-man">Draughts-man</option>
<option value="Receptionist">Receptionist</option>
<option value="Secertary">Secertary</option>
</select><br><br>
Country Applied From:<select name="country">
<option value="">Country...</option>
<option value="Afganistan">Afghanistan</option>
<option value="Albania">Albania</option>
</select><br><br>
Message:<textarea name="comment"></textarea> <br><br>
Upload Your Resume:<input type="file" name="my_file"><span style="color: red; margin-left: -60px;" >*<?php echo $fileErr ?></span><br><br>
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here"><span style="color: red" >*<?php echo $humanErr ?></span><br><br>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Clear"><br><br>
<strong><?php echo $result ?></strong>
</form><br>
</body>
</html>
You have set $check5=1 when allowedExtensions is true. Next to it, you check file_size. When your file_size > 5MB, check5 was not reset or change. So if your attachment is proper & file_size > 5mb system will try to send email with attachment (which you don't want) as check5==1. So to stop it you need to set check5=0 when file_size > 5MB.
Please update your code like :
if($file_size > 5000000){
$fileErr .= "Max allowed size is 5 MB";
} else {
$check6 = 1;
array_push($files,$file);
}
Hope this is clear
Your condition is correct and your code is also working fine. Please recheck.
Try PHPMailer, I am using it there will be no problem.
<?php
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from#example.com', 'First Last');
$mail->addAddress('whoto#example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
$mail->Body = 'My message body';
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'My uploaded file');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>
This is an updated msg's with a working code for sending two different emails using php mailer. It also has working validation server site.
You need to create you own mail class or use the normal one.
Hope someone else can use it two!
Thank you!!
<?php
require"validation.php";
ob_start();
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
$info_email= 'example#example.com';
$info_name = 'Example';
require"PHPMailer/mail.inc.php";
$cams="$name has just made a comment or posted a question";
$camb= "<html>
<head>
<h3> $name has asked the following question or comment on you website:</h3>
</head>
<body>
$comments <br><br><br>
Their information: <br><br>
<table cellspacing=\"4\" cellpadding=\"4\" border=\"1\">
<tr>
<td align=\"center\">Name:</td>
<td align=\"center\"> $name</td>
</tr>
<tr>
<td align=\"center\">Email:</td>
<td align=\"center\"> $email</td>
</tr>
</table>
<br>
<img src=\"cid:mailhead\" alt=\"shop logo used in emails\" />
Pleasy try to reply as soon as possible.<br>
Thank you!!
</body>
</html>";
$mail = new MailCon;
$mail->IsSMTP();
$mail->isHTML(true);
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($info_email, $info_name);
$mail->Subject = $cams;
$mail->MsgHTML($camb);
if ($mail->Send()) {
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
$cums = 'Thank you for using our contact form.';
$message = file_get_contents('mail/example.html');
$message = str_replace('%username%', $name, $message);
$message = str_replace('%email%', $email, $message);
$message = str_replace('%comments%', $comments, $message);
$alt_body="Thank you for asking us a question or making a comment. We will reply as soon as possible.";
$mail = new MailCon;
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->From = $info_email;
$mail->FromName = $info_name;
$mail->AddAddress($email, $name); // Add a recipient
$mail->Subject = $cums;
$mail->MsgHTML($message);
$mail->AltBody = $alt_body;
$mail->Send();
}
ob_end_flush();
?>
This is the validation bit wich you can include using require once.
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 3) {
$error['comments'] = "Please leave a comment.";
}
if (!$error) {
echo "<div class='alert-box success'>Thanks " . $name . ". Your message has been sent.<a href='' class='close' onclick='clearForms()'>×</a></div>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<div class='alert-box alert'>" . $error['name'] . "</div> \n" : null;
$response .= (isset($error['email'])) ? "<div class='alert-box alert'>" . $error['email'] . "</div> \n" : null;
$response .= (isset($error['comments'])) ? "<div class='alert-box alert'>" . $error['comments'] . "</div>" : null;
echo $response;
exit();
} # end if there was an error sending
?>
I have this code for a form
<?php
session_start();
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Register</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<center><table width="1074" height="768" border="0" cellspacing="5" cellpadding="10" div style="width: 1065; height: *px; background:#FFFFFF;">
<tr>
<td bgcolor="#88bbdd">
<body>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<div align="center">
<table>
<form id="registerForm" name="registerForm" method="post" action="register-exec.php">
<tr>
<td><div align="left">*First Name <td><input name="fname" type="text" class="textfield" id="fname" /></div>
<tr>
<td><div align="left">*Last Name <td><input name="lname" type="text" class="textfield" id="lname" /></div>
<tr>
<td><div align="left">*Email Address <td><input name="login" type="text" class="textfield" id="login" /></div>
<tr>
<td><div align="left">*Password <td><input name="password" type="password" class="textfield" id="password" /></div>
<tr>
<td><div align="left">*Confirm Password <td><input name="cpassword" type="password" class="textfield" id="cpassword" /></div>
</tr>
</table>
<br><br>
<input type="submit" name="Submit" value="Register" />
</form>
<br><br>* Indicates a Required Field
</div>
</td>
</tr>
</table>
</body>
</html>
Then that form runs this PHP
<?php
// multiple recipients
$to = $login;
// subject
$subject = 'Subject';
// message
$message = '
<html>
<head>
<title>Email</title>
</head>
<body>
<p>Content</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: $fname $lname. "\r\n";
$headers .= 'From: email#mydomain.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);
$login = clean($_POST['login']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);
//Input Validations
if($fname == '') {
$errmsg_arr[] = 'First name missing';
$errflag = true;
}
if($lname == '') {
$errmsg_arr[] = 'Last name missing';
$errflag = true;
}
if($login == '') {
$errmsg_arr[] = 'Email Address missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($cpassword == '') {
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
//Check for duplicate login ID
if($login != '') {
$qry = "SELECT * FROM members WHERE login='$login'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Login ID already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-form.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO members(firstname, lastname, login, passwd) VALUES('$fname','$lname','$login','".md5($_POST['password'])."')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: register-success.php");
exit();
}else {
die("Query failed");
}
?>
What I want it to do is when someone registers they get an email saying welcome. This does not work I am trying to change the 'to' to the email address they submitted in the form.
Any ideas on how I can Achieve this?
Disclosure: I'm one of the developers behind AlphaMail
I would recommend that you use a Transactional Email Service such as:
AlphaMail
Mailgun
SendGrid
Why?
You don't have to think that much about email delivery.
Statistics. Let's you track Total Sent/Clicks/Opens/Bounces.
Often web service-based instead of SMTP. I.e. easier to handle.
Cleaner code (at least if you use AlphaMail that separates data from presentation).
Scalable and future proof.
If you choose to go with AlphaMail you could use the AlphaMail PHP-client.
Example:
include_once("comfirm.alphamail.client/emailservice.class.php");
$email_service = AlphaMailEmailService::create()
->setServiceUrl("http://api.amail.io/v1")
->setApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
$person = new stdClass();
$person->userId = "1234";
$person->firstName = "John";
$person->lastName = "Doe";
$person->dateOfBirth = 1975;
$response = $email_service->queue(EmailMessagePayload::create()
->setProjectId(12345) // Your AlphaMail project (determines template, options, etc)
->setSender(new EmailContact("Sender Company Name", "from#example.com"))
->setReceiver(new EmailContact("Joe Doe", "to#example.org"))
->setBodyObject($person) // Any serializable object
);
Another advantage with AlphaMail is that you can edit your templates directly in the AlphaMail Dashboard, and you can format your emails using the Comlang template language.
<html>
<body>
<b>Name:</b> <# payload.firstName " " payload.lastName #><br>
<b>Date of Birth:</b> <# payload.dateOfBirth #><br>
<# if (payload.userId != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
Use gmail as your mail server.
require_once('class.phpmailer.php');
include_once('class.smtp.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "<html></html>"; //html stuff
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port
$mail->Username = "id#gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->From = "id#gmail.com";
$mail->FromName = "Admin";
$mail->Subject = "Welcome";
$mail->WordWrap = 50; // set word wrap
$mail->AddReplyTo("id#gmail.com","Admin");
$mail->AddAddress($email_id); //receiver's id
$mail->IsHTML(true); // send as HTML
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if(!$mail->Send()){
$msg = "Mailer Error: ".$mail->ErrorInfo;
header("Location: http://{$_SERVER['HTTP_HOST']}/site/index.php?msg=$msg");
}else{
$msg="Message sent successfully!";
header("Location: http://{$_SERVER['HTTP_HOST']}/site/index.php?msg=$msg");
}
Download class.phpmailer.php and class.smtp.php and keep them in your root
EDIT:
In register-exec.php,
$to = $_POST['login'];
$name = $_POST['fname'];
$password = $_POST['password']; // you've given the name as 'password' in your form
You can use these variables..like
$body = "<div>Hi '.$name.'!<br>Your id:'.$to.',<br>Your Password:'.$password.'</div>";