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>";
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
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
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>
My validation contact form is not working. While I try to submit the form the following error occurs:
Warning: mail() [function.mail]: Failed to connect to mailserver at
"localhost" port 25, verify your "SMTP" and "smtp_port" setting in
php.ini or use ini_set() in
E:\CMS_Site\wamp\www\sitename\contents\send_mail.php on line 53
<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('eWTy3pUA1Okb-4lwUtk4dg');
if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL && isset($_POST['message']) != NULL )
{ // if(isset($_POST['submit_form']) != NULL) IF START
$name = strtoupper (trim($_POST['name']));
$address = trim($_POST['address']);
$email = strtolower(trim($_POST['email']));
$contact = trim($_POST['contact']);
$country = trim($_POST['country']);
$website = trim($_POST['website']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
//---------------------------------------------
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "kiranpahadi#gmail.com";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
$message = stripslashes($message);
$subject = stripslashes($subject);
if($email)
{
$headers = "From: {$name} <{$_REQUEST['email']}>";
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else
{
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){$from_name = stripslashes($_REQUEST['name']);}
$headers = "From: {$name} <{$_REQUEST['email']}>";
}
mail($my_email,$subject,$message,$headers);
?>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<?php
//---------------------------------------------
}
else
{
?>
<script type="text/javascript">
function validate_mail()
{
var mail_name=document.mail_form.name.value;
var mail_email=document.mail_form.email.value;
var mail_contact=document.mail_form.contact.value;
var mail_message=document.mail_form.message.value;
var mail_subject=document.mail_form.subject.value;
var spaceRegxp = /\w+/;
var emailRegxp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var contactRegxp = /^\d+$/;
if (spaceRegxp.test(mail_name) != true){
alert("PLEASE CHECK NAME");
document.mail_form.name.focus();
return false;}
if (emailRegxp.test(mail_email) != true){
alert("PLEASE CHECK EMAIL");
document.mail_form.email.focus();
return false;}
if (contactRegxp.test(mail_contact) != true){
alert("PLEASE CHECK CONTACT NUMBER");
document.mail_form.contact.focus();
return false;}
if (spaceRegxp.test(mail_subject) != true){
alert("PLEASE CHECK Subject");
document.mail_form.subject.focus();
return false;}
if (spaceRegxp.test(mail_message) != true){
alert("PLEASE CHECK MESSAGE");
document.mail_form.message.focus();
return false;}
else {
document.mail_form.action = 'index.php?t=contact&i=25';
document.mail_form.btn_submit.disabled=1;
document.mail_form.btn_submit.value = ' PLEASE WAIT ... ';
document.mail_form.submit();
}
}
</script>
<form name = "mail_form" method="post" enctype="multipart/form-data">
<div><label for="name"> Full Name: </label> <input name="name" type="text" size="50" /> </div>
<div><label for="address"> Address: </label> <input name="address" type="text" size="50" /></div>
<div><label for="email"> Email: </label><input name="email" type="text" size="50" /></div>
<div><label for="contact">Contact:</label> <input name="contact" type="text" size="50" /></div>
<div><label for="country">Country:</label> <input name="country" type="text" size="50" /> </div>
<div><label for="website">Website:</label> <input name="website" type="text" size="50" /> </div>
<div><label for="subject">Subject:</label> <input name="subject" type="text" size="50" /> </div>
<div><label for="message">Your Message:</label>
<textarea name="message" cols="40" rows="8"></textarea>
</div>
<div> <p> <input type="Button" name="btn_submit" id="submit-go" value=" Send Mail " onClick="validate_mail()"/> </p>
</div>
</form>
<?php
}
?>
Your code for sending mail through php has no issue at all.
if you are using WAMP in windows ,their will not have any SMTP server setup. so if you need to send mail from WAMP you need to use any SMTP server support.You can use Mandrill Mailchimb to send Email from localhost by just create an a/c in it, download swift files and add it in your working directory to setup mail server.To read-more on how to send mail through mandrill see below code..
or
You can work this code in a live server which supports SMTP setup.
Sending Mail via Mandrill Swift files in your code.You can change message subject etc as your own.
send_mail.php
<?php
if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL && isset($_POST['message']) != NULL ){
$name = strtoupper (trim($_POST['name']));
$address = trim($_POST['address']);
$email = strtolower(trim($_POST['email']));
$contact = trim($_POST['contact']);
$country = trim($_POST['country']);
$website = trim($_POST['website']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
//---------------------------------------------
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "kiranpahadi#gmail.com";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])){
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){
$errors[] = "Email address is invalid";
}
else{
$exploded_email = explode("#",$_REQUEST['email']);
if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){
$errors[] = "Email address is invalid";
}
else{
if(substr_count($exploded_email[1],".") == 0){
$errors[] = "Email address is invalid";
}
else{
$exploded_domain = explode(".",$exploded_email[1]);
if(in_array("",$exploded_domain)){
$errors[] = "Email address is invalid";
}
else{
foreach($exploded_domain as $value){
if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){
$errors[] = "You must enable referrer logging to use the form";
}
// Check for a blank form.
function recursive_array_check_blank($element_value){
global $set;
if(!is_array($element_value)){
if(!empty($element_value)){
$set = 1;
}
}
else{
foreach($element_value as $value){
if($set){
break;
}
recursive_array_check_blank($value);
}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){
$errors[] = "You cannot send a blank form";
}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){
foreach($errors as $value){
print "$value<br>";
}
exit;
}
if(!defined("PHP_EOL")){
define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");
}
// Build message.
function build_message($request_input){
if(!isset($message_output)){
$message_output ="";
}
if(!is_array($request_input)){
$message_output = $request_input;
}
else{
foreach($request_input as $key => $value){
if(!empty($value)){
if(!is_numeric($key)){
$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;
}
else{
$message_output .= build_message($value).", ";
}
}
}
}
return rtrim($message_output,", ");
}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
$message = stripslashes($message);
$subject = stripslashes($subject);
if($email){
$headers = "From: {$name} <{$_REQUEST['email']}>";
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else{
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){
$from_name = stripslashes($_REQUEST['name']);
}
$headers = "From: {$name} <{$_REQUEST['email']}>";
}
include_once "swift/lib/swift_required.php";
$from = array("frommail#mail.com" => "Your Name");
$to="kiranpahadi#gmail.com";
$message = "Hello -This is a test mail";
$subject = "Subject – Test";
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername('kiranpahadi#gmail.com');
$transport->setPassword('eWTy3pUA1Okb-4lwUtk4dg');
$swift = Swift_Mailer::newInstance($transport);
sleep(2);
$html = "" . $message . "";
$maildetails = new Swift_Message($subject);
$maildetails->setFrom($from);
$maildetails->setBody($html, 'text/html');
$maildetails->setTo($to);
$maildetails->addPart($message, 'text/plain');
if ($recipients = $swift->send($maildetails, $failures)) {
echo 'Message successfully sent!';
} else {
echo "There was an error:n";
//print_r($failures);
}
//mail($my_email,$subject,$message,$headers);
?>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<?php
}
else{
?>
<form name = "mail_form" method="post" action ="send_mail.php"enctype="multipart/form-data">
<div><label for="name"> Full Name: </label> <input name="name" type="text" size="50" /> </div>
<div><label for="address"> Address: </label> <input name="address" type="text" size="50" /></div>
<div><label for="email"> Email: </label><input name="email" type="email" size="50" /></div>
<div><label for="contact">Contact:</label> <input name="contact" type="text" size="50" /></div>
<div><label for="country">Country:</label> <input name="country" type="text" size="50" /> </div>
<div><label for="website">Website:</label> <input name="website" type="text" size="50" /> </div>
<div><label for="subject">Subject:</label> <input name="subject" type="text" size="50" /> </div>
<div><label for="message">Your Message:</label>
<textarea name="message" cols="40" rows="8"></textarea>
</div>
<div><p><input type="submit" name="btn_submit" id="submit-go" value="Send Mail"/></p></div>
</form>
<?php
}
?>
# i just removed some of the unwanted lines from your code..
You can download swift files from http://ajesh.co.in/downloads/swift.zip
WAMP does not have an SMTP server.
Explanation
To be able to send email you need an outgoing email server. In most Linux systems there exists one by default, and PHP will use sendmail, a Linux app for submitting mail to whichever mail transfer agent you have installed.
In Windows, to be able to send mail from PHP you need an outgoing mail server somewhere and you need to tell PHP the address and port of it. This is done in php.ini using the SMTP and smtp_port settings. It will default to 'localhost' on port 25. Unless you have set up a mail server on that machine, that will fail.
If your ISP gives you an outgoing mail server, for example, you could use its address and port number. Or, if you're serious about sending mail, you'd set up your own mail server on the local machine or someone in your local network.
SOURCE Why mail() PHP function does not work with WAMP default installation?