Got this HTML contact form:
<form action="contact.php" method="get">
Nombre<br>
<input type="text" name="cf_name"><br>
Email<br>
<input type="text" name="cf_email"><br>
Mensaje<br>
<textarea name="cf_message"> </textarea><br>
<input type="submit" value="Enviar">
</form>
And a separate php file sending contact info:
$mail_to = 'tienda#shambricolage.com';
$subject = 'Mensaje de Contacto de Sham Bricolage - '.$field_name;
$body_message = 'Persona de contacto: '.$field_name."\n";
$body_message .= 'E-mail de contacto: '.$field_email."\n";
$body_message .= 'Mensaje: '.$field_message;
$headers = 'De: '.$field_email."\r\n";
$headers .= 'Responder a: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
window.location = 'contacto.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar. Por favor, contacte por email a tienda#shambricolage.com');
window.location = 'contacto.html';
</script>
<?php
}
?>
On form submit, page does not load and web keeps loading with no email sending at all. You can check this on http://www.shambricolage.com/Contacto.html when submiting form, nothing loads.
Done on a tool called Webpage Maker
I've changed a bit. Dont know if it works. But its messed up and not well programmed.
HTML:
<form action="contact.php" method="GET">
Nombre<br>
<input type="text" name="cf_name"><br>
Email<br>
<input type="text" name="cf_email"><br>
Mensaje<br>
<textarea name="cf_message"> </textarea><br>
<input type="submit" value="Enviar">
</form>
PHP:
ob_start();
$field_name = $_GET['cf_name'];
$field_email = $_GET['cf_email'];
$field_message = $_GET['cf_message'];
$mail_to = 'tienda#shambricolage.com';
$subject = 'Mensaje de Contacto de Sham Bricolage - '.$field_name;
$body_message = 'Persona de contacto: '.$field_name."\n";
$body_message .= 'E-mail de contacto: '.$field_email."\n";
$body_message .= 'Mensaje: '.$field_message;
$headers = 'De: '.$field_email."\r\n";
$headers .= 'Responder a: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
</script>
<?php
header('Location: contacto.html');
}
else { ?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar. Por favor, contacte por email a tienda#shambricolage.com');
</script>
<?php
header('Location: contacto.html');
}
?>
Finally, after contacting hosting team, it was an STMP server and I had to fill a complete PHP mail file with aditional information, as seen on here.
<?php
error_reporting( E_ALL & ~( E_NOTICE | E_STRICT | E_DEPRECATED ) ); //Aquí se genera un control de errores "NO BORRAR NI SUSTITUIR"
require_once "Mail.php"; //Aquí se llama a la función mail "NO BORRAR NI SUSTITUIR"
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];
$to = 'tienda#shambricolage.com'; //Aquí definimos quien recibirá el formulario
$from = 'tienda#shambricolage.com'; //Aquí definimos que cuenta mandará el correo, generalmente perteneciente al mismo dominio
$host = '217.116.0.228'; //Aquí definimos cual es el servidor de correo saliente desde el que se enviaran los correos
$username = 'tienda.shambricolage.com'; //Aqui se define el usuario de la cuenta de correo
$password = '****'; //Aquí se define la contraseña de la cuenta de correo que enviará el mensaje
$subject = 'Mensaje de la tienda Shambricolage'; //Aquí se define el asunto del correo
$body = 'Persona de contacto: '.$field_name."\n";
$body .= 'E-mail de contacto: '.$field_email."\n";
$body .= 'Mensaje: '.$field_message;
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar el mensaje. Por favor, escriba a tienda#shambricolage.com');
window.location = 'index.html';
</script>
<?php
} else {
?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
window.location = 'index.html';
</script>
<?php
}
?>
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
HTML Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>BuddyTeam | Website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<img src="images/title.png" alt="BuddyTeam | Website" /><br /><br />
<div id="contact-area">
<form method="post" action="contactengine.php">
<p style="text-align:right" onclick="alert('Só podes registar uma conta secundária se tiveres uma principal! Neste espaço escreve o Nickname da tua conta registada no Servidor.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Nickname"></label>
<p><font face="serif"></font></p><input type="text" name="Nickname" id="Nickname" placeholder="Informa o Nickname da conta principal registada no Servidor." required />
<p style="text-align:right" onclick="alert('Para não haver fraudes precisamos de saber que és mesmo tu! Vai ao Servidor com a tua conta registada, usa o comando ( /meuid ) e escreve os números neste espaço.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="ID"></label>
<p><font face="serif"></font></p><input type="text" name="ID" id="ID" placeholder="Informa o ID da conta principal registada no Servidor." required />
<p style="text-align:right" onclick="alert('Contas nunca são demais! Neste espaço escreve o Nickname da nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Novo"></label>
<input type="text" name="Novo" id="Novo" placeholder="Informa o Nickname da conta que pretendes registar." required />
<p style="text-align:right" onclick="alert('Segurança em primeiro lugar! Neste espaço escreve uma senha para a nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Senha"></label>
<input type="text" name="Senha" id="Senha" placeholder="Informa uma senha para a tua nova conta." required />
<p style="text-align:right" onclick="alert('Depois entra em contacto! Coloca aqui o teu Email para seres contacto quando a conta for registada.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Email"></label>
<input type="text" name="Email" id="Email" placeholder="Informa um Email para contacto.">
<input type="submit" name="submit" value="Enviar" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</div>
</body>
</html>
PHP Code:
<?php
$EmailFrom = "geral#buddyplays.net";
$EmailTo = "geral#buddyplays.net";
$Subject = "Novo Pedido de Registo de Conta";
$Nickname = Trim(stripslashes($_POST['Nickname']));
$ID = Trim(stripslashes($_POST['ID']));
$Novo = Trim(stripslashes($_POST['Novo']));
$Senha = Trim(stripslashes($_POST['Senha']));
$Email = Trim(stripslashes($_POST['Email']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Conta Registada: ";
$Body .= $Nickname;
$Body .= "\n";
$Body .= "ID da Conta Registada: ";
$Body .= $ID;
$Body .= "\n";
$Body .= "Nova Conta: ";
$Body .= $Novo;
$Body .= "\n";
$Body .= "Senha: ";
$Body .= $Senha;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=concluido.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
}
?>
When I fill out the form and submit, I'm redirected to "erro.html" and the email is not sent. What is wrong?
The system stops working from one moment to another without me doing any kind of editing.
What do I need to change for the system to work again?
The problem is that your mail() function isn't working because you have supplied an invalid fourth parameter (as your From address). "From: <$EmailFrom>" shouldn't have the brackets around the email address. If you do make use of the brackets, you need to supply a name in front of them.
Instead of $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
What you're looking to do is add it as a header:
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: ' . $Nickname. ' <' . $EmailFrom . '>';
$success = mail($EmailTo, $Subject, $Body, $headers);`
This will evaluate to: From: $Nickname <$EmailFrom>.
Also note that some mail servers prevent the From address from being manipulated in order to prevent phishing.
You're getting a 404 simply because erro.html doesn't exist on your server. Creating the relevant file will resolve the error and redirect you there automatically when there's an error sending of the email.
Hope this helps! :)
i am making a website where you can send tips to a email but the tip is shown as a whole block and not with paragraphs while the tip is shown with paragraphs at the website?
Here u can see it in the email:
Email
Here is the php code i use to send the email:
if(!is_a($entry, WP_Error) && rgar($entry, '2') == $_GET['email']) {
$toEmail = $_GET['email'];
$fromName = get_option('blogname');
$fromEmail = get_option('admin_email');
$to = $toEmail;
$subject = 'Hierbij uw eerste tip: '.$recent_posts[0]["post_title"];
$headers = "From: ".$fromName." <".$fromEmail.">\r\n";
$headers .= "Reply-To: ".$fromEmail."\r\n";
if(isset($ccMail) && $ccMail!=""){$headers .= "CC: ".$ccMail."\r\n";}
if(isset($BccMail) && $BccMail!=""){$headers .= "Bcc: ".$BccMail."\r\n";}
$headers .= 'X-Mailer: PHP v'.phpversion()."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8";
$message = '<html><body>';
$message .=
'<a href="http://inreach.nl" target="_blank" style="text-decoration:none">
<img src="http://inreach.nl/wp-content/themes/new_inreach/images/logo-inreach-grey.png" alt="Inreach-name" /></a><br><br>
Beste '.rgar($entry, 1).',<br><br>
Hebbes!
<br><br>
Jouw leiderschapsontwikkeling is gestart met deze eerste tip voor effectiever leiderschap. Veel succes met het inzetten van de kennis!<br><br>
<b>'.$recent_posts[0]["post_title"].'</b><br><br>
<div ><img style="max-width:100%" src="'.$image[0].'" alt="photo"/></div><br><br>
'.$recent_posts[0]["post_content"].' <br><br><br><br>
Wil jij over een specifieke situatie of case een tip? Mail me dan! Binnen twee dagen krijg je een persoonlijke reactie waar je mee verder kan.
<br><br>
Weet jij anderen die baat kunnen hebben bij deze tips? Stuur deze mail dan door naar ze! Zij kunnen zich aanmelden door HIER te klikken.
<br><br>
Hartelijke groet,
<br><br>
Steven Brouwers
<br><br>
p.s.: toch afmelden? Dat kan HIER ';
$message .= '</body></html>';
$sent = wp_mail($to,$subject,$message,$headers);
If think it's not a problem about paragraphs. Assuming $recent_posts[0]["post_content"] is a string with \n for new lines, you could try to use nl2br.
Replace:
$recent_posts[0]["post_content"]
With:
nl2br($recent_posts[0]["post_content"])
It should work. If not, try to inspect what's in $recent_posts[0]["post_content"].
try putting the following code before wp_mail();
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
use table instead of div in your $message.
it will work then
The form action is linked to this php script:
<?php
$email = $_POST['subscribefield'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Dit adres klopt niet";
die();
}
$to = "flash1996mph#hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";
mail($to, $subject, $body);
echo "U bent succesvol aangemeld voor de Vandenberg nieuwsbrief";
echo $_SERVER['REMOTE_ADDR'];
?>
At the end i added echo $_SERVER['REMOTE_ADDR']; then i checked my mail, but there was nothing. Did i use the code the wrong way?
EDIT:
<?php
$email = $_POST['subscribefield'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Dit adres klopt niet";
die();
}
$to = "flash1996mph#hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";
$body .= $_SERVER['REMOTE_ADDR'];
mail($to, $subject, $body);
echo "U bent succesvol aangemeld voor de Vandenberg nieuwsbrief";
?>
The above is an edit^
When mail is called the email is sent. In your script $body is the body of the email so append the IP address on to that variable before you call the mail function.
$to = "flash1996mph#hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";
$body .= $_SERVER['REMOTE_ADDR'];
mail($to, $subject, $body);
The echo currently just outputs the IP on the browser.
I'm quite new to php and am trying to make a simple form that mails the form-data to a specified mail address. I used this script here and modified it to my needs but when I try it out it just does nothing. It will go to the php page but nothing else happens and the page is empty.
Here is my HTML form:
<form class="contact" name="contact" method="post" action="./files/php/contact_send.php">
<table id="form">
<tr>
<td class="data-right"><label for="naam"><b>NAAM</b></label></td>
<td class="data-left">
<input type="text" name="naam" size="50" style="border-style:inset"/>
</td>
</tr>
<tr>
<td class="data-right"><label for="mailadres"><b>E-MAILADRES</b></label></td>
<td class="data-left">
<input type="text" name="mailadres" size="50" style="border-style:inset"/>
</td>
</tr>
<tr>
<td class="data-right"><label for="boodschap"><b>BOODSCHAP</b></label></td>
<td class="data-left">
<textarea name="boodschap" cols="39" rows="4" style="border-style:inset"></textarea>
</td>
</tr>
</table>
<input type="image" src="./files/img/stuur.png"
onmouseover="this.src='./files/img/stuur-hover.png'"
onmouseout="this.src='./files/img/stuur.png'"
alt="Stuur" width="150px" name="submit" value="Submit" />
</form>
and my php code:
<?php
if(isset($_POST['mailadres'])) {
// CHANGE THE TWO LINES BELOW
$email_to = "blabla#gmail.com";
$email_subject = "Contact";
function died($error) {
// your error code can go here
echo "Het spijt ons maar er is iets fout gelopen bij het versturen van het formulier";
echo "Hieronder zijn de fouten weergegeven:<br /><br />";
echo $error."<br /><br />";
echo "Verbeter de fouten en probeer opnieuw.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['naam']) ||
!isset($_POST['mailadres']) ||
!isset($_POST['boodschap'])) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
$naam = $_POST['naam']; // required
$mailadres = $_POST['mailadres']; // required
$boodschap = $_POST['boodschap']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$mailadres)) {
$error_message .= 'Het e-mailadres dat u heeft opgegeven is geen geldig e-mailadres.<br />';
}
$naam_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($naam_exp,$naam)) {
$error_message .= 'De naam die u heeft opgegeven is geen geldige naam.<br />';
}
if(strlen($boodschap) < 5) {
$error_message .= 'De opgegeven boodschap is niet lang genoeg, gelieve minstens 5 letters te gebruiken.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Formulier details:\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Naam: ".clean_string($naam)."\n";
$email_message .= "E-mail: ".clean_string($mailadres)."\n";
$email_message .= "Boodschap: ".clean_string($boodschap)."\n";
// create email headers
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/' phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.
<?php
}
die();
?>
You have a syntax error at this line:
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/' phpversion();
You forgot a dot in your string concatination at phpversion(). Change it to:
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/'. phpversion();
The reason why you got an empty screen is because php is probably not displaying the error. This is a security measure. You can force php to report and display the errors by adding the next lines to the top of your script:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
You should remove these lines in a production environment because it is a security risk.
Replace:
if(!isset($_POST['naam']) ||
!isset($_POST['mailadres']) ||
!isset($_POST['boodschap'])) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
with:
if ( (!isset($_POST['naam'])) ||
(!isset($_POST['mailadres'])) ||
(!isset($_POST['boodschap'])) ) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
You were missing a lot of brackets for this statement.
Also, change the bottom part from:
?>
Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.
<?php
}
die();
?>
To:
echo "Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.";
}
die();
?>
i have a contact.php form that works very well, but i have a problem with that form, the messages like alerts, etc, are showing in the file contact.php itself, i want that when i hit the "Send" button, the php puts a eccho to say the message without leaving the site.
Heres my contact.php
<?php
if(isset($_POST['email'])) {
$email_to = "natestale#gmail.com";
$email_subject = "Nuevo contacto de Sitio web";
function died($error) {
// Mensaje de error
echo "Disculpas, pero ha ocurrido un(os) error(es) con lo datos del formulario. ";
echo "El o los errores son los siguientes.<br /><br />";
echo $error."<br /><br />";
echo "Por favor corrija los errores.<br /><br />";
die();
}
// validacion de campos
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['message'])) {
died('Disculpas, pero ha ocurrido un(os) error(es) al enviar el formulario.');
}
$name = $_POST['name']; // obligatorio
$email = $_POST['email']; // obligatorio
$website = $_POST['website']; // no obligatorio
$prioritycase = $_POST['prioritycase']; // no obligatorio
$asunto = $_POST['asunto']; // no obligatorio
$message = $_POST['message']; // obligatorio
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$error_message .= 'La direccion de E-mail es incorrecta.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$name)) {
$error_message .= 'EL nombre no es un nombre Valido.<br />';
}
if(!preg_match($string_exp,$website)) {
$error_message .= 'La url no es valida.<br />';
}
if(strlen($message) < 2) {
$error_message .= 'El comentario no parece estar completo.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Nombre: ".clean_string($name)."\n";
$email_message .= "Website: ".clean_string($website)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .= "Mensaje: ".clean_string($message)."\n";
// estructura del correo
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<meta http-equiv="refresh" content="3;URL=http://www.redpandastudio.tk" />
<link rel="stylesheet" type="text/css" href="dist/css/contacto.css" />
<!-- incluimos nuestro mensaje de agradecimiento -->
<?php
}
?>
And here is my website with the contact form working.
http://redpandastudio.tk/
The easy solution is to put your validation from your file contact.php into the file where you have the form itself. When pressing submit make it post to the same file. Moreover, add to your validation logic this line:
// to find out if submit btn was pressed - which means that somebody clicked the button
if(isset($_POST["submit"])){
....
}
Another option is to use $SESSION. How to use Sessions for validation is very nicely explained here.