I want to encode my php sending form in my language.
What is wrong with the code? I have added the content-type in the $headers at the end... It is not the whole file, there is also HTML after the PHP, but did not let me to post it
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "gancho_lambev#abv.bg";
$email_subject = "Contact Form...";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form your submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form your submitted.');
}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers .= 'Content-type: text/plain; charset=windows-1251' . "\r\n";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers); ;}
?>
For sending mails in different language, you can just change the charset:
$headers .= 'Content-type: text/plain; charset=UTF-8' . "\r\n";
$headers .= 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
And be sure the page is encoded as UTF-8 and that if a database is used, the table ( or whole db ) is in "UTF-8 unicode general"
With UTF-8 you can write the characters as they appear, don't use entities.
Do you mean something like this. Hope it helps
Try using a 3rd party library, like phpmailer:
Example: http://phpmailer.worxware.com/index.php?pg=exampleamail
Download: http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/PHPMailer%20v5.1/
Don't forget to set the charset, like this:
<?php
require_once '../class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
$mail->CharSet = 'utf-8';
try {
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Try the following:
Set the collation of your database/ tables/ rows to UTF-8. UTF8_general_ci should do.
Set the connection between MySQL and PHP to UTF-8. (By executing the query SET NAMES 'utf8' after connecting or by setting the default connection encoding).
Try sending the content-type header with PHP: header("Content-Type: text/html; charset=utf-8");.
Related
I'm trying to send emails with attachment from a HTML form using PHP mail().
I have found a script online that works - but with one problem:
If a file is attached to the email, the script works fine. However, if there is no attachment, the email is sent but doesn't contain any text content (blank email body).
I want the ability to add an attachment to be optional.
My question is, how can an email be sent successfully, with or without an attachment?
Thanks!
The PHP script I'm using is as follows:
<?php
$email = trim($_POST['email']);
$email_san = filter_var($email, FILTER_SANITIZE_EMAIL);
$fname = $_POST['first_name'];
$fname_san = filter_var($fname,FILTER_SANITIZE_STRING);
$lname = $_POST['last_name'];
$lname_san = filter_var($lname,FILTER_SANITIZE_STRING);
$org = trim($_POST['organisation']);
$org_san = filter_var($org,FILTER_SANITIZE_STRING);
$user_phone = $_POST['phone'];
$trim_phone = trim($user_phone);
$replace_phone = preg_replace('/[^0-9+-]/', '', $trim_phone);
$phone_san = filter_var($replace_phone,FILTER_SANITIZE_NUMBER_INT);
$message = $_POST['message'];
$fromemail = $email_san;
$subject="Inquiry";
$email_message = '<p><b>First Name:</b> '.$fname_san.'</p>
<p><b>Organisation:</b> '.$org_san.'</p>
<p><b>Email:</b> '.$email_san.'</p>
<p><b>Phone:</b> '.$phone_san.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
$semi_rand = md5(uniqid(time()));
$headers = "From: ".$fromemail;
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
if($_FILES["file"]["name"]!= ""){
$strFilesName = $_FILES["file"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message .= "\n\n";
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: application/octet-stream;\n" .
" name=\"{$strFilesName}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$strContent .= "\n\n" .
"--{$mime_boundary}--\n";
}
$toemail="email#somedomain.com";
if(mail($toemail, $subject, $email_message, $headers)){
echo "Email sent.";
}else{
echo "Email NOT sent.";
}
?>
/*** UPDATE ***/
OK, taking advice that PHPMailer is a better method of sending emails, I have made another attempt to setup PHPMailer.
I don't have Composer so I downloaded and installed PHPMailer manually. I don't have Composer so I downloaded and installed PHPMailer manually. My server folder hierarchy is shown in this image.
I found a PHPMailer tutorial online which provided a simple script which I saved as 'mailer-test.php', uploaded and linked to my PHPMailer install:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once "php-mailer/src/Exception.php";
//PHPMailer Object
$mail = new PHPMailer(true); //Argument 'true' in enables exceptions
//From email address and name
$mail->From = "me#mydomain.com";
$mail->FromName = "Full Name";
//To address and name
//$mail->addAddress("recipient#somedomain.com", "Recepient Name");
$mail->addAddress("recipient#somedomain.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("me#mydomain.com", "Reply");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
However, when I view 'mailer-test.php' in a browser, I get the follwing server error:
This page isn't working.
yourdomain.com is currently unable to handle this request.
HTTP ERROR
What is causing this?
Something look strange with your strcontent (he miss the $ on line 39)
But to get more simple, use PhpMailer class
It makes your life easy by sending mails
Make sure you add enctype='multipart/form-data' to your form tag:
<form action='index.php' method='POST' enctype='multipart/form-data'>
...
</form>
Hello guyz and thank you in advance. I have made an email form using php to send an email through a form from my website
Although the form works fine and the emails are sent I have a problem when I sent a message in my native language (Greek). If I write the message in English everything is fine and the email is view-able. If I send a message in Greek then the email is sent , but looks like this :
³Î¾ÏƒÎ»Î´Î³Î·ÎºÎ»ÏƒÎ´ ασλαηκσλκαςξδςακσ³Î¾ÏƒÎ»Î´Î³Î·ÎºÎ»ÏƒÎ´ ασλαηκσλκαςξδςακσ
Here is the code I use in my php form :
<?php
if(isset($_POST['email'])) {
$email_to = "info#something.gr";
$email_subject = "Email Form - WebSite";
function died($error) {
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
$first_name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['message']; // required
$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 .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<center>
Thank you for contacting us. We will be in touch with you very soon.</br>
You will be redirected to our homepage in 5 seconds </center>
<script type="text/javascript">
setTimeout("window.location='/'",5000);
</script>
<?php
}
?>
The problem is with character encoding.
By default, PHP E-mails are sent with ISO-8859-1.
You'll need to swap to UTF-8 for languages like Greek :)
Fortunately, you can set this in the headers:
$headers = "Content-Type: text/html; charset=UTF-8";
Combined with your existing headers:
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'Content-Type: text/html; charset=UTF-8' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
Hope this helps!
I am using the below PHP code that takes values from an HTML form and sends an email in HTML. This works fine for me.
Now I need to add an ATTACHMENT field that will send the attachment along with the email (with or without storing the file on the server). Can someone please suggest how to do it with or without PHPmailer?
Thanks!
<?php
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['address'])) {
die('Error: Missing variables');
}
$name=$_POST['name'];
$mobile=$_POST['mobile'];
$position=$_POST['position'];
$email=$_POST['email'];
$message=$_POST['message'];
$ip=$_SERVER['REMOTE_ADDR'];
$to="email#server.com";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers = 'From: '.$_POST['name'].' <'.$_POST['email'].'>';
'X-Mailer: PHP/' . phpversion();
$subject='Job Application from '.$name."\n\n\n";
$body.='Name: <b>'.$name."</b><br>\n";
$body.='Mobile No: <b>'.$mobile."</b><br>\n";
$body.='Position: <b>'.$position."</b><br>\n";
$body.='Email: <b>'.$email."</b><br>\n";
$body.='Message: <b>'.$message."</b><br>\n";
$body.='IP address of the submitter: '."\n".$ip."\n";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$email."\r\n";
if(mail($to, $subject, $body, $headers)) {
header("Location: thank-you.html");
} else {
echo "Something has gone wrong! Please try again!";
}
?>
It's easier to use PHPMailer..
You can get the documentation and tutorial here.
This is the code for a basic mail and attaching files:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Hope this helps.
$filePath = 'foldername/attachment.zip';
$file = fopen($filePath,'rb');
$data = fread($file,filesize($filePath));
fclose($file);
$data = chunk_split(base64_encode($data));
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$data
Add this code before this line "if(mail($to, $subject, $body, $headers)) {".
I am trying to get contact form details through mail. But failed to do so using mail() function. here's my code.
if(isset($_POST['rqsubmit'])) {
$name = htmlspecialchars($_POST['Field1']);
$email = trim($_POST['Field2']);
$phone = trim($_POST['Field3']);
$msg = strip_tags($_POST['Field4']);
//echo $name." ".$phone." ".$email." ".$msg;
$to = 'gowtham#gmail.com';
//$from = $email;
$subject = "Software Development";
$message = "Name:".$name."<br/>Phone".$phone."<br/>Message:".$msg;
//echo $message;
$semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//echo $message;
$headers = "From: xyz#gmail.com". "\r\n".
'Reply-To: xyz#gmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$ok = #mail($to, $subject, wordwrap($message, 70, "\r\n"), $headers);
if ($ok) {
echo "<p>Thank you for contacting us! !!</p>";
} else {
echo "<p>Mail could not be sent. Sorry!</p>";
}
} else {
echo "mail not sent";
}
I would like to know where i am going wrong. Any help would b highly appreciated. thank you!
Add:
'X-Mailer: PHP/' . phpversion();
to:
$headers
Perhaps it's being rejected due to the lack of a sender email address.
Put your own email address in the From: header, and add a Reply-To: header containing the sender's address.
Can I just point out that you need to check the form data thoroughly before putting it into an email. For example, I could quite easily send emails all over the place by setting Field2 to something like blah#example.com\nBcc: spam1#spam.com, spam2#spam.com, ....
EDIT:
Sorry, my mistake — you did add a From header. However, it's quite likely that your mail server is configured to reject emails where the sender address is not on its list of approved senders. That's why you need to put your own address in the From: header, and the sender's address in the Reply-To: header.
EDIT 2:
Also, what on earth are you doing with $mime_boundary? As far as I can tell, you're not sending a valid MIME message.
I want to use php mailer for sending multiple attachment in mail.
But the problem is, how to use it. Where to download it, how to install it,. I have searched for 3 days, but have got confused, two or three tutorials that i used, doesn't work and make me more confused.
I want a single file tag, that uploads multiple attachments , and send them in email.
I have done with the Email sending with one attachment successfully..
Please guide me. And please give those links that really work for the purpose.
PHPMailer can be downloaded from its SourceForge page.
Now to the code, which is mostly taken from the examples provided in the ZIPball:
<?php
require_once 'class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->AddAddress('whoto#otherdomain.com', 'John Doe');
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML(file_get_contents('contents.html'));
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
This is a combination of multiple scripts and a bit of reading. I haven't added any form processing or the like, but it allows for the use of the option to attach multiple files through one input button. Hope its helpful to someone. I'm sure it breaks all kinds of standards. I do know it works in Chrome 31 and IE10.
Edit: Working with this little script, I added HTML formatting for the message and the thank you message replacement.
<?php
if(isset($_POST['Submit'])) {
$email_to = "";
$email_subject = "";
$thankyou = "thanks.html";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
function died($error) {
echo "Sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
$requester_name = $_POST['requester_name']; // required
$requester_email = $_POST['requester_email']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "<html><body> \r\n";
$email_message .= "<table style=\"border: 1px #777 solid; font-family: Arial; font-size: 13px;\" cellpadding=\"7\"> \r\n";
$email_message .= "<tr><td style=\"background: #444; color:#fff;\"><strong>New Hire Form</strong></td><td style=\"background: #444; color:#fff;\">Requirements</td></tr>" . "\n";
$email_message .= "<tr><td style=\"background: #ccc;\"><strong>Requester Name: </strong></td><td style=\"background: #ddd;\">" .clean_string($requester_name). "</td></tr>" . "\n";
$email_message .= "<tr><td style=\"background: #ccc;\"><strong>Requester Email: </strong></td><td style=\"background: #ddd;\">".clean_string($requester_email). "</td></tr>" . "\n";
$email_message .= "</table> \r\n";
$email_message .= "</body></html>";
// multipart boundary
$email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message . "\n\n";
for($i=0;$i<count($_FILES['attachfile']['name']);$i++)
{
if($_FILES['attachfile']['name'][$i] != "")
{
//here you will get all files selected by user.
$name = ($_FILES['attachfile']['name'][$i]);
$tmp_name = ($_FILES['attachfile']['tmp_name'][$i]);
$type = ($_FILES['attachfile']['type'][$i]);
$size = ($_FILES['attachfile']['size'][$i]);
echo count($_Files['attachfile']) ;
echo $_FILES['attachfile']['name'][$i] ;
echo $_FILES['attachfile']['tmp_name'][$i] ;
echo $_FILES['attachfile']['type'][$i] ;
// Read the file content into a variable
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
// Close the file
fclose($file);
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$headers .= 'From: '.$email_sender."\r\n". // Mail will be sent from your Admin ID
'Reply-To: '.$Email."\r\n" . // Reply to Sender Email
'X-Mailer: PHP/' . phpversion();
// headers for attachment
$headers .= "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
#mail($email_to, $email_subject, $email_message, $headers);
?>
<script>location.replace('<?php echo $thankyou;?>')</script>
<?php
}
die();
?>