Email form is messing up UTF-8 text [duplicate] - php

This question already has answers here:
How to send UTF-8 email?
(3 answers)
Closed 3 years ago.
I have a PHP form on my website. It collects text strings from HTML input elements, then sends the text to my mailbox. However, when people type in text in other languages, the email appears garbled. The text appears to be okay in the Web browser. There's even some JavaScript code that gets/sets some of these form fields, and seems to do so correctly.
Maybe the PHP code is not treating the text as unicode? Or the text gets sent to my mailbox using the wrong encoding? I would appreciate some help, thanks.
I have already added
header("Content-Type: text/html; charset=utf8");
to the top of the PHP files.
Here is a part of the PHP form that gets the inputted values using POST.
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$titletxt = $_POST["titletxt"];
$titleurl = $_POST["titleurl"];
$legend = $_POST["legend"];
$command = $_POST["command"];
$binding = $_POST["binding"];
$layout = $_POST["layout"];
Here is a part of the PHP form that emails me the text:
mail
(
"blahblah#blah.com",
"VGKD Bindings Submission",
"NAME:\t\t" . $name . "\n" .
"EMAIL:\t\t" . $email . "\n" .
"MESSAGE:\t" . $message . "\n" .
"GAME TITLE:\t" . $titletxt . "\n" .
"GAME URL:\t" . $titleurl . "\n" .
"LAYOUT:\t\t" . $layout . "\n\n" .
"LEGENDS:\n" . $legend . "\n\n" .
"COMMANDS:\n" . $command . "\n\n" .
"BINDINGS:\n" . $binding . "\n\n"
);

Please, try to add utf-8 charset header to your mail function, for example
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <example#example.com>' . "\r\n";
$headers .= 'Cc: example#example.com' . "\r\n";
mail
(
"blahblah#blah.com",
"VGKD Bindings Submission",
"NAME:\t\t" . $name . "\n" .
"EMAIL:\t\t" . $email . "\n" .
"MESSAGE:\t" . $message . "\n" .
"GAME TITLE:\t" . $titletxt . "\n" .
"GAME URL:\t" . $titleurl . "\n" .
"LAYOUT:\t\t" . $layout . "\n\n" .
"LEGENDS:\n" . $legend . "\n\n" .
"COMMANDS:\n" . $command . "\n\n" .
"BINDINGS:\n" . $binding . "\n\n",
$headers
);
The header() function sends a raw HTTP header to a client browser, but mail function with the variable $headers sends headers to email.

Related

Send multiple images in email using mail()

I stored the images in url format in database.now i want to send mail with multiple images using mail() in php
$sql11 = "SELECT `photo_id`, `project_id`, `map_id`, `map_flag`, `user_id`, `photo_path`, `pdf_path`, `created_at`, `modified_at` FROM `photos` WHERE map_flag='Task' and map_id='$task_id'";
$rl = $conn->query($sql11);
while ($res11 = mysqli_fetch_assoc($rl)) {
$array[] = [$res11['photo_path']];
}
$str = implode(',', $array);
$message = $message_content . "\n" . "\n" . "\n" . $message1 . "\n" . $message2 . "\n" . $message3 . "\n" . $message4 . "\n" . $message5 . "\n" . $message6 . "\n" . $array . "\n" . $message8 . "\n";
$from = "123#test.com";
$headers = 'From: ' . $from . "\r\n";
$result = mail($to, $subject, $message, $headers);
First off, you need to tell the email app that this is html. This can be done by adding the line
$headers .= "Content-type: text/html; charset=UTF-8";
Next, what is photo_path? Does it also include the full url or a relative url? You need to set the full url i.e. http://example.com/{$res11['photo_path']}

PHP email form with attachments not working

I'm trying to use a PHP email form I found online that supports attachments, with a bit of extra code, but it's not working, I get a message saying "Sent", but no emails (I checked spam already).
Here is the php file:
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
if(count($files) > 0){
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderMail;
//send email
$mail = #mail($to, $subject, $message, $headers, $returnpath);
//function return true, if email sent, otherwise return fasle
if($mail){ return TRUE; } else { return FALSE; }
}
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'someEmail#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['files'];
$subject = 'Customer Contact From Service Form';
$html_content = $message;
//call multi_attach_mail() function and pass the required arguments
$send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files);
//print message after email sent
echo $send_email?"<h1> Mail Sent</h1><br>".$message:"<h1> Mail not SEND</h1>";
My form looks like this:
<form NOVALIDATE action="processContact.php" enctype="multipart/form-data" id="claimsForm" method="post" name="claimsForm">
..lots of fields...
<div class="form-group">
<label class="control-label claimsForm-field-header" for="customerTry">Photos:</label>
<input type="file" id="files[]" name="files[]" multiple="multiple" />
</div>
<input class="green-btn" id="ss-submit" name="submit" type="submit" value="Submit">
</form>
The function came with the form I downloaded, so I don't think there is a problem with it. I've been playing around with the code and trying different things, but no luck (I'm not a PHP guy).
EDIT:
Based on the suggestion below, I tried using phpMailer, following the example they have, here is my php file now:
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'murtorius#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['userfile'];
$subject = 'Customer Contact From Service Form';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require 'php-mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom($from, $from_name);
$mail->addAddress($to, 'TEST');
$mail->Subject = $subject;
$mail->msgHTML($message);
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'Photos');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
I changed the input file field name to 'userfile[]', but I get this:
Warning: sha1() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 35
Warning: move_uploaded_file() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 36
If I change the name to 'userfile' (without []) I get a blank screen and no email.

Accept and Decline button is not working in mail

I am sending a mail after user submits form to approve are disapprove the data through link in mail. Here is the code:
$subject = 'User needs approval';
$message = 'The user $empname needs your approval' .
'----------------------------------- ' . "\r\n" .
'Accept: ' . $accept_link . "\r\n" .
'Decline: ' . $decline_link . "\r\n";
$_headers = 'From:admin#yourwebsite.com' . "\r\n"; // Set FROM headers
//mail($supemail, $subject, $message, $headers); // Send the email
fnMail($supemail,"mailb#mail.com"," Web master","reimbursement Form",$message);
The link to accept and decline is:
$accept_link = "http://communique/elegant-contact-form/quick-contact/ajax/approval.php?e=" . $empemail . "&h=" . hash('sha512', 'ACCEPT');
$decline_link = "http://communique/elegant-contact-form/quick-contact/ajax/approval.php?e=" . $empemail . "&h=" . hash('sha512', 'DECLINE');
and here is the approval.php file:
$hash = $_GET['h'];
$email = $_GET['e'];
if($hash == hash('sha512', 'ACCEPT')){
$res=execQuery('oth','update form set approved=1 where empemail="$email"');
if(count($res)>0){
fnMail($email,"mk.web#mattsenkumar.com","MattsenKumar Web master","Contact Front registration",'APPROVED');
}
}else if($hash == hash('sha512', 'DECLINE')){
fnMail($email,"mk.web#mattsenkumar.com","MattsenKumar Web master","Contact Front registration",'DECLINE');
}
But I got the mail like this:
The user $empname needs your approval----------------------------------- Accept: Decline:
This is day-1 basic PHP syntax: variables are not interpolated into single-quoted strings. Read the docs, do this:
$message = "The user $empname needs your approval" .
For the accept and deny links to be included in the message you must define them before you use them, like this:
$accept_link = "http://communique/elegant-contact-form/quick-contact/ajax/approval.php?e=" . $empemail . "&h=" . hash('sha512', 'ACCEPT');
$decline_link = "http://communique/elegant-contact-form/quick-contact/ajax/approval.php?e=" . $empemail . "&h=" . hash('sha512', 'DECLINE');
$message = "The user $empname needs your approval" .
'----------------------------------- ' . "\r\n" .
'Accept: ' . $accept_link . "\r\n" .
'Decline: ' . $decline_link . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
Try setting the headers
or check this below stackoverflow link
hope this will help
PHP mail() - How to put an html link in an email?

PHP String concatenation and New Lines

I need a bit of help understanding some PHP behavior that is not making sense to me, thanks in advance for the help.
First off, is there a difference between the use of \r\n and \n\r? I would think logically no, but I am thinking there has to be a practical reason why they are listed in the PHP document separately. I am currently using \r\n but sometimes I get a line break, sometimes I don't, its befuddling.
Second, I am aware that if I was echoing the information inside the browser, I would use the nl2br() function but I am not showing the information to the browser, it is being gathered and concatenated into a string that is then being sent via mail() and that's where the visual discrepancy is showing up.
Here is the script, pretty straight forward, nothing mind boggling here:
<?php
$browser = $_SERVER['HTTP_USER_AGENT'];
$page = $_SERVER['PHP_SELF'];
$ip = $_SERVER['REMOTE_ADDR'];
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$from_page = $_SERVER['HTTP_REFERER'];
$time = date('l, F jS Y - g:i:s A', $_SERVER['REQUEST_TIME']);
$uri = $_SERVER['SCRIPT_URI'];
$to = "***";
$subject = "Visitor Log";
$message = "IP Address : " . $ip . " ( HOST: " . $host . " )\r\n" . "Browser : " . $browser . "\r\n" . "From : " . $from_page . "\r\n" . "Page : " . $page . "\r\n" . "Time : " . $time . "\r\n" . "Script : " . $uri;
$headers = "From: ***" . "\r\n" . "Reply-To: ***" . "\r\n" . "X-Mailer: PHP/" . phpversion();
mail($to,$subject,$message,$headers);
?>
But as you can see, I have linebreaks that are padded into the $message for obvious readability of the email that I receive. But sometimes the emails arrive and everything is on a separate line as should be and sometimes it doesn't. So I thought maybe the method of adding a line break is not the best and that I am doing something wrong.
So the question is, what should I use to get the proper line breaks, if what I am using is not correct, and if it is correct, why isn't it always working? Your assistance to add some clarity to this would be greatly appreciated.
If it matters or makes a difference, I am using PHP 5 (5.5.28) Linux server with Apache.
UPDATED ANSWER
Thank you for everyone's help but ultimately I ended up fixing it as follows and even added the content type for good measure (TY #TOM).
<?php
$browser = $_SERVER['HTTP_USER_AGENT'];
$page = $_SERVER['PHP_SELF'];
$ip = $_SERVER['REMOTE_ADDR'];
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$from_page = $_SERVER['HTTP_REFERER'];
$time = date('l, F jS Y - g:i:s A', $_SERVER['REQUEST_TIME']);
$uri = $_SERVER['SCRIPT_URI'];
$to = "***";
$subject = "Visitor Log";
$message = "IP Address : " . $ip . " ( HOST: " . $host . " )" . "\r\n";
$message .= "Browser : " . $browser . "\r\n";
$message .= "From : " . $from_page . "\r\n";
$message .= "Page : " . $page . "\r\n";
$message .= "Time : " . $time . "\r\n";
$message .= "Script : " . $uri;
$headers = "From: ***" . "\r\n";
$headers .= "Reply-To: ***" . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "Content-Type: text/html; charset=\"utf-8\"" . "\r\n";
mail($to,$subject,nl2br($message),nl2br($headers));
?>
NOTE: The new formatting is not part of the solution, its just for myself. The solution is giving up on plain and going with html and using nl2br function to force the breaks, not elegant, not what I wanted entirely but works.
my best guess is that you sometimes send as text/plain and sometimes as text/html.. (since you do not specify anything, maybe the mail() or mailserver or client takes a best guess? you could investigate..)
i would try to force it to send as text/html and use
<br/>
's with nl2br, or force it as text/plain and use \n
like...
$message = "IP Address : " . $ip . " ( HOST: " . $host . " )\r\n" . 'Content-Type: text/html; charset="utf-8"'."\r\n"."Browser : " . $browser . "\r\n" . "From : " . $from_page . "\r\n" . "Page : " . $page . "\r\n" . "Time : " . $time . "\r\n" . "Script : " . $uri;
..if that's how you force it to mail as html, im not sure about the header
The thing is that you are not passing the content-type in the email header, so the email client could interpret it like plain-text or text/html depending of the vendor. The best is to pass the content-type as parameter in the email header.
content-type:text/plain: \n as line break
content-type:text/html: </br> as line break

HTML elements in PHP

I am very new to PHP, so be gentle.
It seems I cant run HTML in PHP.
For example when I try to
echo "<script> success(); </script>";
Result will be:
<script> success(); </script>
Another example:
$msg2 = "<b>Dear</b> ".$name ."\n\n" ."Thank you for your registration, we will be contacting you within 48h."."\n\n" ."Yours ....";
Result will be:
<b>Dear</b> (name of the client)
Thank you for your registration, we will be contacting you within 48h.
Yours ....
I checked the meta its:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
I will give You guys the code ( some of it is in Estonian )
<?php
if (isset($_REQUEST['email'], $_REQUEST['nimi'], $_REQUEST['koolitus'], $_REQUEST['telf'], $_REQUEST['kuupaev'], $_REQUEST['tingimused'])) {
$admin_email = "ville.madison#gmail.com";
$email = $_REQUEST['email'];
$koolitus = $_REQUEST['koolitus'];
$nimi = $_REQUEST['nimi'];
$kuupaev = $_REQUEST['kuupaev'];
$telf = $_REQUEST['telf'];
$marked = $_REQUEST['marked'];
$kodulehemail = "koolitused#registreerumine.ee";
$koolitaja = $_REQUEST['koolitaja'];
$beauty = "info#beautyfactory.ee";
$msg = "Koolitusele registreerumine: " . $koolitus . "\n" . "Soovitud koolitaja: " . $koolitaja . "\n\n" . " Nimi: " . $nimi . "\n" . " Email: " . $email . "\n" . " Telefon: " . $telf . "\n" . " Soovitud kuupäev (aaaa-kk-pp): " . $kuupaev . "\n\n" . "Märked: " . $marked;
$msg2 = '<b>Hea</b> ' . $nimi . "\n\n" . "Täname Teid koolitusele broneerimast, teatame Teile registreeringu kinnitamisest 48h jooksul." . "\n\n" . "Teie Beauty Factory";
mail($admin_email, "Koolitusele registreerumine", $msg, "From:" . $kodulehemail);
mail($email, "Koolitusele registreerumine", $msg2, "From:" . $beauty);
}
?>
At the moment there is only one word that I am trying to make in bold for the sake of testing. But when I get it working I will start editing it more and I want to echo a javascript function in the php if statement.
I have tried using single quotes, double quotes and the:
nl2br(htmlentities($msg2));
None of it works
The message you send is not interpreted as HTML. The default
header of the mail function is text/plain.
If you want your customers to see the bold text, you must specify the content-type as HTML in the message header.
<?php
// Set the content type of the email to HTML (and UTF-8)
$header = 'Content-type: text/html; charset=utf-8' . "\r\n";
// Add the from field
$header .= 'From: ' . $beauty . "\r\n";
// Send email
mail ($email, "Koolitusele registreerumine", $msg2, $header);
?>
However you will not be able to use Javascript as it is intepreted client side. PHP does not interpret Javascript, and most of the mail clients will not execute Javascript for obvious security reasons.
Here is a sample example of how to use html tags in php:
<?php
var $name = "xyz";
var $email = "xyz#gmail.com";
echo '<table border="1" style="width:20%">';
echo '<tr><th>UserName</th><th>Email</th></tr><tr><td>';
echo $name."<br>";
echo '</td><td>';
echo $email."<br>";
echo '</td></tr></table>';
?>
This is basic php and html table format example,you can follow this for write html tags.
The problem was that the function mail() had a default content of text/plain, just needed the $header to make text/html. Thanks guys for your quick answers !

Categories