I am having some trouble, I am trying to submit a form with php and phpmailer.
So what I did is trying to make a form following w3school complete form example and then I wondered if I could send it through email. I found phpmailer and I tried using it but it is not sending.
I am using the $contactsend to know if I can send form or not (after the validation have been done). So in case $contactsend is 0 then I cannot send and if it is 1 then I can send the form.
However I am almost sure that there is an issue with it but I don't know why.
How can I understand what is going wrong?
Here is the code I have :
<?php
$contactnameErr = $emailErr = $phoneErr = $subjectErr = $messageErr = "";
$contactname = $email = $phone = $subject = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$contactsend= 1;
if (empty($_POST["contactname"])) {
$contactnameErr = "* Name is required";
$contactsend= 0;
} else {
$contactname = test_input($_POST["contactname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactname)) {
$contactnameErr = "* Only letters and white space allowed";
$contactsend= 0;
}
}
if (empty($_POST["contactemail"])) {
$contactemailErr = "* Email is required";
$contactsend= 0;
} else {
$contactemail = test_input($_POST["contactemail"]);
// check if e-mail address is well-formed
if (!filter_var($contactemail, FILTER_VALIDATE_EMAIL)) {
$contactemailErr = "* Invalid email format";
$contactsend= 0;
}
}
if (empty($_POST["contactphone"])) {
$contactphoneErr = "* Phone is required";
$contactsend= 0;
} else {
$contactphone = test_input($_POST["contactphone"]);
$contactsend= 0;
}
if (empty($_POST["contactsubject"])) {
$contactsubjectErr = "* Subject is required";
$contactsend= 0;
} else {
$contactsubject = test_input($_POST["contactsubject"]);
$contactsend= 0;
}
if (empty($_POST["contactmessage"])) {
$contactmessageErr = "* Message is required";
$contactsend= 0;
} else {
$contactmessage = test_input($_POST["contactmessage"]);
$contactsend= 0;
}
echo $contactsend;
if($contactsend== 1)
{
//send mail
$message = "\nSpecial Events , Contact Us . \nName : " . $contactname . "\nEmail : " . $contactemail . "\nPhone : " . $contactphone
. "\nSubject : " . $contactsubject ."\nMessage : " . $contactmessage;
require("/home/specialeventsleb/public_html/phpmailer/PHPMailer/class.phpmailer.php");
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'email1';
$mail->Password = 'password1';
$mail->SetFrom('email1', 'FromEmail');
$mail->AddAddress('email1', 'ToEmail');
$mail->AddAddress('email2', 'ToEmail1');
$mail->AddAddress('email3', 'ToEmail2');
$mail->SMTPDebug = true;
$mail->Timeout = 2000;
$mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
$mail->Debugoutput = 'echo';
$mail->Subject = 'Message from Special Events Website';
$mail->Body = $message;
$mail->send();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="ContactUs">
<!--<img class="ComputerBanner" src="Pictures/map/ContactUsBanner.png" />-->
<img class="MobileBanner" src="Pictures/map/ContactUsBannerMobile.png" />
<div class="ContactBox">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2>SEND US A MESSAGE!</h2>
<span>We'd be happy to hear from you.</span>
<input name="contactname" placeholder="Name" type="text" value="<?php echo $contactname;?>"/> <span class="error"> <?php echo $contactnameErr;?></span>
<input name="contactemail" placeholder="Email" type="text" value="<?php echo $contactemail;?>" /><span class="error"> <?php echo $contactemailErr;?></span>
<input name="contactphone" placeholder="Phone #" type="text" value="<?php echo $contactphone;?>" /><span class="error"> <?php echo $contactphoneErr;?></span>
<input name="contactsubject" placeholder="Subject" type="text" value="<?php echo $contactsubject;?>" /><span class="error"> <?php echo $contactsubjectErr;?></span>
<textarea name="contactmessage" placeholder="Message"><?php echo $contactmessage;?></textarea><span class="error"> <?php echo $contactmessageErr;?></span>
<input type="submit" name="submit" value="Send" class="contact-button" />
</form>
</div>
</div>
First the operations you're checking with if($contactsend== 1) are not called because your script forces $contactsend = 0 checking "contactsubject", "contactphone", "contactmessage"..
Then you have to set these
$mail->SetFrom('email1', 'FromEmail');
$mail->AddAddress('email1', 'ToEmail');
$mail->AddAddress('email2', 'ToEmail1');
$mail->AddAddress('email3', 'ToEmail2');
with valid email addresses..
Example with
$mail->AddAddress($contactemail, 'ToEmail');
which get the value from the POST
For any other infos read this
https://github.com/PHPMailer/PHPMailer
Related
I want to send emails with the help of PHPMailer. The goal is to use PHPMailer, connect with their host and get messages. But I get the error code: Undefined type 'PHPMailer\PHPMailer\PHPMailer'
Already used all kinds of tricks to get it working, but I can't seem to figure it out. Here is m code for reference.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require '/vendor/autoload.php';
$errors = [];
$errorMessage = '';
if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name)) {
$errors[] = 'Name is empty';
}
if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}
if (empty($message)) {
$errors[] = 'Message is empty';
}
if (!empty($errors)) {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
} else {
$phpmailer = new PHPMailer(true);
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.mailtrap.io';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 2525;
$phpmailer->Username = '***';
$phpmailer->Password = '***';
$mail->setFrom($email, 'Mailtrap Website');
$mail->addAddress('test#mailtrap.io', 'Me');
$mail->Subject = 'New message from your website';
// Enable HTML if needed
$mail->isHTML(true);
$bodyParagraphs = ["Name: {$name}", "Email: {$email}", "Message:", nl2br($message)];
$body = join('<br />', $bodyParagraphs);
$mail->Body = $body;
echo $body;
if($mail->send()){
header('Location: thank-you.html'); // redirect to 'thank you' page
} else {
$errorMessage = 'Oops, something went wrong. Mailer Error: ' . $mail->ErrorInfo;
}
}
}
?>
<html>
<body>
<form action="/swiftmailer_form.php" method="post" id="contact-form">
<h2>Contact us</h2>
<?php echo((!empty($errorMessage)) ? $errorMessage : '') ?>
<p>
<label>First Name:</label>
<input name="name" type="text" value="dima"/>
</p>
<p>
<label>Email Address:</label>
<input style="cursor: pointer;" name="email" value="dima#dima.com" type="text"/>
</p>
<p>
<label>Message:</label>
<textarea name="message">dima</textarea>
</p>
<p>
<input type="submit" value="Send"/>
</p>
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js"></script>
<script>
const constraints = {
name: {
presence: {allowEmpty: false}
},
email: {
presence: {allowEmpty: false},
email: true
},
message: {
presence: {allowEmpty: false}
}
};
const form = document.getElementById('contact-form');
form.addEventListener('submit', function (event) {
const formValues = {
name: form.elements.name.value,
email: form.elements.email.value,
message: form.elements.message.value
};
const errors = validate(formValues, constraints);
if (errors) {
event.preventDefault();
const errorMessage = Object
.values(errors)
.map(function (fieldValues) {
return fieldValues.join(', ')
})
.join("\n");
alert(errorMessage);
}
}, false);
</script>
</body>
</html>
I am trying to send email to more than 2 emails if it is possible with the bellow code, but currently with the code i have i can only send to 1 email but i want to send it more than 4 users. Also i will fetch users from a database but right now it is not a problem for me, id prefer solving the first one
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'example#domain.co'; //Sets SMTP username
$mail->Password = 'xxxxxxxxxxx'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = 'name'; //Sets the From name of the message
$mail->AddAddress($_POST["email"]); //Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["subject"]; //Sets the Subject of the message
$mail->Body = $_POST["message"]; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for contacting us</label>';
}
else
{
$error = '<label class="text-danger">There is an Error</label>';
}
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send an Email on Form Submission using PHP with PHPMailer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<div class="row">
<div class="col-md-8" style="margin:0 auto; float:none;">
<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
<br />
<?php echo $error; ?>
<form method="post">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>```
you have multiple choice here, in first you can create a list of email input like by adding email[1] in your input component.
<input type="email" name="email[1]" value="<? $email[1] ?>" >
The number is used to identify the input in your php ,like this $_POST[email][x].
In the " back-end " section, you will add a loop around
foreach($_POST['email] as $emailAdress){
$mail->addAdress($emailAdress)
}
i hope that will help you
As I am beginner in using PHPmailer trying to send mail in localhost (XAMPP) server. I included class.phpmailer.php and class.smtp.php file but I'm getting an error message "there is an error" To resolve this I changed gmail account IMAP settings as Enable and and allow less secure apps.
But the problem has been not resolved. I get:
Warning:fwrite() expects parameter 1 to be resource, integer given in C:\xampp\htdocs\email-phpmailer\class\class.smtp.php on line 1023
Code I have Tried
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
require 'class/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts of your Email hosting, this for Godaddy
$mail->Port = '587'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'abc#gmail.com'; //Sets SMTP username
$mail->Password = 'MyPass'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('xyz#gmail.com', 'its me'); //Adds a "To" address
//$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["subject"]; //Sets the Subject of the message
$mail->Body = $_POST["message"]; //An HTML or plain text message body
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for contacting us</label>';
}
else
{
$error = '<label class="text-danger">There is an Error</label>';
}
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Send an Email on Form Submission using PHP with PHPMailer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<div class="row">
<div class="col-md-8" style="margin:0 auto; float:none;">
<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
<br />
<?php echo $error; ?>
<form method="post">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" value="Submit" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
I'm trying use honeypot technique for my custom form on wordpress site.
My form look like that.
<form id="form-1"
action="<?php echo get_template_directory_uri(); ?>/mail.php" method="post" class="order__form form">
<p class="form__title">Order and Receive 30% off</p>
<p class="form__text">fill out this form so you can get sale</p>
<input type="text" name="name" class="form__item" placeholder="Your name">
<input type="email" name="email" required class="form__item" placeholder="Email address">
<p class="robotic" id="pot">
<label>If you're human leave this blank:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<input type="submit" value="Send" class="button form__button">
</form>
Input with name robotest for validation on server side.
This is mail.php code:
<?php
$mess = '';
$mess .= '<hr>';
if($_POST['robotest'] != ''){
$error = "You are a gutless robot.";
} else {
if(isset($_POST['name'])) {
$name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
$mess .= '<b>Имя отправителя: </b>' . $name . '<br>';
}
if(isset($_POST['email'])) {
if($_POST['email']!=''){
$email = substr(htmlspecialchars(trim($_POST['email'])), 0, 100);
$mess .= '<b>E-mail: </b>' . $email . '<br>';
}
}
}
$mess .= '<b>Заявка пришла со страницы:</b> ' . $_SERVER["HTTP_REFERER"] .'<br>';
$mess .= '<hr>';
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->AddAddress('xxx2xxx.com','');
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = "new";
$mail->From = "new";
$mail->FromName = "new";
$mail->Body = $mess;
if ($mail->Send()) {
header('Location: ../');
} else {
die ('Mailer Error: ' . $mail->ErrorInfo);
}
header("Location: /thanks/");
?>
When I add validation for robotest, this script doesn't work.
You are setting the $error variable but you are not using it anywhere.
If you change the:
$error = "You are a gutless robot.";
To a:
die( "You are a gutless robot." );
You will have what you describe you want to have.
i am trying to send a random number to an email but unable to this is the code that i have been able to come up with so far
please help if possible
sendmail.php
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}
index.php
<form action = "register.php" method="POST">
<p>Username</p>
<input type="text" name="username" maxlength="40" value='<?php if(isset($username)) echo $username ?>'"><br>
<p>New Password</p>
<input type="password" name="password">
<p>email</p>
<input type="text" name="email" maxlength="40" value='<?php if(isset($email)) echo $email ?>'"> <br><br>
<input type="submit" value="Register"> <br><br>
</form>
In form(index.php)
<form action="sendmail.php" method="post">
<lable>email</lable>>
<input type="text" name="email" maxlength="40">
<br>
<input type="submit" value="Register">
</form>
In sendmail.php
$rand= rand(10, 20)// random number generator
$to = $_POST['email'];
$header ='From:admin#domain.com';
$subject ='Verification Code';
$message = "Your Random number is";
$message .= $rand;
$message .= "Thank you-Admin";
if(empty($to))
{
echo "Email is Empty";
}
else
{
if (mail($to,$subject,$message,$header)){
echo 'Check Your Email FOr verfication code';
}
else{
echo 'Failed';
}
}
You forgot to add semicolon at the end of first line
$rand= mt_rand(100000, 999999)
It should be
$rand= mt_rand(100000, 999999);
I think the hosting service that You're using does not accept sending using mail() functions. Maybe for security reasons to prevent virus-like php scripts to send spams from Your account.
So create admin#domain.com email account and using PHPMailer send Your email:
require __DIR__.'/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.hostname.com';
$mail->SMTPAuth = true;
$mail->Username = 'no-reply#domain.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('admin#domain.com');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
download link and examples here: https://github.com/PHPMailer/PHPMailer