I have a little problem with the following code. When I click "Send" it says "PHP Warning: mail() [function.mail]: "sendmail_from" not set in php.ini or custom "From:" header missing in C:***.com**\mail.php on line 21"
This is the jQuery:
$(document).ready(function(){
$("#send").click(function(){
var valid = '';
var isr = ' requested.</h6>';
var name = $("#name").val();
var mail = $("#email").val();
var messaggio = $("#message").val();
if (name.length<1) {
valid += '<h6>A valid name is'+isr;
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<h6>A valid e-mail address is'+isr;
}
if (valid!='') {
$("#re").fadeIn("slow");
$("#re").html("<h6><b>Error:</b></h6>"+valid);
$("#re").css("background-color","#ffc0c0");
}
else {
var datastr ='name=' + name + '&mail=' + mail + '&messaggio=' + encodeURIComponent(messaggio);
$("#re").css("display", "block");
$("#re").css("background-color","#FFFFA0");
$("#re").html("<h6>Sending..</h6>");
$("#re").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
});
function send(datastr){
$.ajax({
type: "POST",
url: "mail.php",
data: datastr,
cache: false,
success: function(html){
$("#re").fadeIn("slow");
$("#re").html(html);
$("#re").css("background-color","#e1ffc0");
setTimeout('$("#re").fadeOut("slow")',2000);
}
});
}
And the PHP
<?php
$mail = $_POST['mail'];
$name = $_POST['name'];
$text = $_POST['messaggio'];
$ip = $_SERVER['REMOTE_ADDR'];
$to = "admin#****.com";
$message = "E-mail received from: ".$name.", ".$mail.".<br />";
$message .= "Messaggio: <br />".$text."<br /><br />";
$message .= "IP: ".$ip."<br />";
$headers = "From: $mail \n";
$headers .= "Reply-To: $mail \n";
$headers .= "MIME-Version: 1.0 \n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \n";
if(mail($to, $message, $headers)){
echo "<h6>Message sent.</h6>";
}
else{
echo "<h6>Ops! We've got a problem! :(</h6>";
}
?>
The mentioned line is "if(mail($to, $message, $headers)){" but I don't understand the error.
I am using the same code on another website (another domain also) and it runs without problems.
Headers need to be terminated with \r\n not \n.
$headers = "From: $mail \r\n";
$headers .= "Reply-To: $mail \r\n";
$headers .= "MIME-Version: 1.0 \r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \r\n";
Also there is a Header Injection vulnerability in your code. You should validate all of the post data that you put into email headers.
Have you checked the SMTP Settings in PHP.INI?
Set this in your code or in your php.ini:
<?php
ini_set("SMTP","smtp-server-address" );
ini_set('sendmail_from', 'from-email-address');
?>
And if you are sending through a different port than 25, you can also override the default:
ini_set('smtp_port', '2525');
You might try replacing your FROM headers with:
$headers = "From: $name <$mail>\r\n";
designating the email address within lt/gt brackets.
One other thought is to be sure the $_POST['mail'] value is indeed being passed.
I think you might have a carriage return coming from your field. You need to scrub your data input in the $_POST like:
$mail = trim($_POST['mail']);
You might also want to use mysql_real_escape_string or something similar in regexp if inputting into a DB.
Also for consistantcy in your code:
$headers = "From: ".$mail." \r\n";
$headers .= "Reply-To: ".$mail." \r\n";
Also I think your missing the correct mail parameters. According to the mail documentation your missing a subject parameter:
mail($to, $subject, $message, $headers);
Related
I have a simple contact form that I want to submit to an email.
Everything is working fine except that instead of the input values being sent in the body of the email it's sending a file.
I tried changing the content-type of my php file but the only thing that changes is the format of the file that's sent, .html or .txt.
It's my first time working with ajax or PHP, so what am I doing wrong here?
I tried inserting the html tags on the message $body and tried without them as well, same thing happens.
Here's my jquery
$("#enviar").click(function(){
$.ajax({
dataType:'html',
url:"./scripts/email.php",
type:"POST",
data:({nome:$("input[name='name']").val(),email:$("input[name='email']").val(),telefone:$("input[name='phone']").val()}),
beforeSend: function(data){
}, success:function(data){
alert("Dados Enviados");
}, complete: function(data){}
});
});
And here's the PHP
<?php
if(isset($_POST['email']) && !empty($_POST['email'])){
$nome = strip_tags($_POST['nome']);
$email = strip_tags($_POST['email']);
$telefone = strip_tags($_POST['telefone']);
$headers = "MIME-Version: 1.1\n";
$headers .= "Content-type: text/html: charset=UTF-8\n";
$headers .= "From: mexample#example.com\n";
$headers .= "Return-Path: example#example.com\n";
$headers .= "Reply-To: ".$email."\n";
$emailsender = "example#example.com";
$to = "receiver email";
$subject = "Formulario - Contato";
$body = "<html>
<head>
<title> Formulario </title>
</head>
<body>".
"<p>". "Nome: " .strip_tags($nome). "</p>".
"<p>". "Email: " .strip_tags($email). "</p>".
"<p>"."Telefone: " .strip_tags($telefone). "</p>".
"</body>
</html>";
if(!mail($to, $subject, $body, $headers ,"-r".$emailsender)){
$headers .="Return-Path: " . $emailsender . "\n";
mail($to, $subject, $body, $headers);
}
}
?>
Here my code. I could not display errors message. Simply mail is not sent. What's wrong with this approach ?
<a id="target" href="http://www.mylink.wav">mylink</a>
<script type="text/javascript">
$(function() {
$("#target").mousedown(function() {
$.post(
"sendemail.php",
{ name: "John" }
);
});
});
</script>
<?php
if($_POST)
{
$mail = "myemail.email.com"
$name = $_POST['name'];
$subject = 'My subject';
$to = "myemail#email.com";
$message = "My message: ".$name."<br />";
$headers = "From: $mail \n";
$headers .= "Reply-To: $mail \n";
$headers .= "MIME-Version: 1.0 \n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1 \n";
}
?>
Thank you for your suggestions to solve this issue.
Firstly check if you actually are calling your script inside jQuery block.
Second, you need to include php mail() function (if enabled on server):
mail($to, $subject, $message, $headers);
http://php.net/manual/en/function.mail.php
I have the following function for sending an email:
function send_email($email){
$subject = "TITLE";
$message = "HERE IS THE MESSAGE";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <emaily>' . "\r\n";
mail($email,$subject,$message,$headers);
}
Instead of $message being a string, I want to call in the file email.html which holds my template.
I have added this:
require 'email.html';
But how can I call in the file?
$message = [call in email.html here]
Require is used when you want to call functions within another php file, or when you want to include some data to an HTTP response.
For this problem, file_get_contents('email.html') is the preferred option. This would be the method I would use:
function send_email($email){
$subject = "Subject of your email";
$message = "";
if(file_exists("email_template.html")){
$message = file_get_contents('email_template.html');
$parts_to_mod = array("part1", "part2");
$replace_with = array($value1, $value2);
for($i=0; $i<count($parts_to_mod); $i++){
$message = str_replace($parts_to_mod[$i], $replace_with[$i], $message);
}
}else{
$message = "Some Default Message";
/* this likely won't ever be called, but it's good to have error handling */
}
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <doNotReply#myDomain.com>' . "\r\n";
$headers .= "To: <$email>\r\n";
$header .= "Reply-To: doNotReply#myDomain.com\r\n";
mail($email,$subject,$message,$headers);
}
I modified your code a little bit and added in both the file_get_contents and file_exists. file_exists confirms that the file is there. If it's not, it avoids the potential error from trying to read it in and can be changed to use some default. My next addition was a for loop. In the $parts_to_mod array, enter in the default values from the template that need to be replaced. In the $replace_with array, put in the unique values that you want to replace parts of the template with.
As an example where I use this, I have a template URL for one of my programs that says id=IDENTIFIER&hash=THEHASH so in my program, my parts_to_mod says $parts_to_mod = array("IDENTIFIER", "THEHASH"); and my replace_with says $replace_with = array($theUsersIdentifier, $theUsersHash);. It then enters the for-loop and replaces the those values in parts_to_modify with the values in replace_with.
Simple concepts and they make your code much shorter and easier to maintain.
Edit:
Here is some sample code:
Let's the say the template is:
<span>Dear PUTNAMEHERE,</span><br>
<div>PUTMESSAGEHERE</div>
<div>Sincerely,<br>PUTSENDERHERE</div>
So, in your php code you'd say:
$parts_to_mod = array("PUTNAMEHERE", "PUTMESSAGEHERE", "PUTSENDERHERE");
$replace_with = array($name, $theBodyOfYourEmail, $whoYouAre);
just use file_get_contents('email.html') This method returns a string with the file contents
You can use this function to call custom email template.
function email($fields = array(),$name_file, $from, $to) {
if(!empty($name_file)) {
$mail_tem_path = 'templates/mails/mail--'.$name_file.'.php'; //change path of files and type file.
if(file_exists($mail_tem_path)) {
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-Type: text/html;charset=UTF-8". "\r\n";
// Additional headers
$headers .= "From:".$fields["subject_from"]." <$from>". "\r\n";
$headers .= "Content-Transfer-Encoding: 8Bit". "\r\n";
$message = file_get_contents($mail_tem_path);
$message = preg_replace("/\"/", "'", $message);
foreach ($fields as $field) {
// Replace the % with the actual information
$message = str_replace('%'.$field["name"].'%', $field["value"], $message);
}
$send = mail($to, $fields["subject"], $message, $headers);
} else {
$send = mail($to, "Error read mail template", "Contact with admin to repair this action.");
}
} else {
$send = mail($to, "Error no exist mail template", "Contact with admin to repair this action.");
}
return $send;
}
Template html
<html>
<body>
TODO write content %value_on_array%
</body>
</html>
Array and execute function.
$fields = array(
"subject" => "tienda_seller_subject",
"subject_from" => "tienda_email_subject_from",
0 => array(
"name" => "value_on_array",
"value" => "result before change"
),
);
//email($fields = array(),$name_file, $from, $to);
email($fields, 'admin', 'owner#email.com', 'client#email.com');
Result
Can I use this part to send mails?
So if I add some php code in action.php, is this sufficient for a working email script (apart from the php code)?
This is the code, (and it's in a function don't worry this is not everything on the page)
And I know there is not a subject field, but I'll just enter the name (voornaam).
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
$.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
document.getElementById('goed').innerHTML = 'Verstuurd!';
PHP support send mail function if the web server have correct setting,
try to research for this.
And you can use plugin like PHPmailer too.
The following is a simple example to send html email use mail function.
Just put the code into action.php will be OK.
<?php
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$telefoonnummer = $_POST['telefoonnummer'];
$email = $_POST['email'];
$subject = 'Sample mail';
$headers = 'MIME-Version: 1.0' ."\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$content = '<html><header><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </header><body>';
$content .= $voornaam;
$content .= $achternaam;
$content .= $telefoonnummer;
$content .= '</body></html>';
mail($email, $subject, $content, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
?>
Ive got a contact form that isnt sending but is outputting that the message is sent? Can anybody see a problem?
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "myemail#email.co.uk";
//begin of HTML message
$message = "
From : $name,
Email: $email,
Subject: $subject,
Message: $message ";
//end of message
// To send the HTML mail we need to set the Content-type header.
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Website Enquiry";
if (isset($_POST['name'])) {
// now lets send the email.
mail($to, $subject, $message, $headers);
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=Thankyou, we will be in touch shortly.');
} else {
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=There was an error sending your message, Please try again.');
}
?>
The "From" header should have a syntactically correct email address. You also need to check the return value of the "mail" function.
$header .= "From: Website Enquiry <enquiry#website.com>";
PS: Please improve your code formatting.
Try to enter an email at From: in $headers.
Like $headers .= "From: youremail#provider.com" or
$headers .= "From: Website Enquiry <youremail#provider.com>"
And you should change it to
if(mail(...)) {
//success
}
else {
//email failed
}