French characters not displaying correctly in PHP mail - email

I have a basic PHP mail form, but whatever I do, I cannot seem to get the characters to display correctly once sent, if the language is written with French accents.
The example sentence I am using is:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
But it comes out as:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
As you can see, the characters with accents are screwed up, once they are received in the email.
I am processing my message variable as such:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
I am then, sending it like so:
$cc = "example#example.com";
$subject = "Website Enquiry";
$message = '<html><body>';
$message .= "<p><strong>Enquiry</strong><br />" . nl2br($fieldenquiry) . "</p>";
$message .= "</body></html>";
$headers = "From: " . $fieldemail . "\r\n";
$headers .= "Cc: " . $cc . "\r\n";
$headers .= "Reply-To: ". $fieldemail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
I'm not a PHP developer by any means. The form works in the sense that it sends etc, but I cannot figure out why the characters mess up. I am encoding the POST variable and I am sending the HTML format with a UTF-8 charset.
Help and guidance appreciated.
Michael.
EDIT:
I figured this out. See my answer below.

I figured it out if anyone is in need of a similar piece of help:
I changed this line:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
To this:
$fieldenquiry = utf8_encode(htmlentities($_POST['fieldenquiry'], ENT_QUOTES, "UTF-8"));
I use the htmlentities() function with UTF-8 specified in the arguments.
This fixed the issue completely. Hope it helps someone.

Related

How to make a email calendar invite automatically accepted (php)?

I'm sending a calendar invite via email but I want it automatically be accepted.
Is there something I can change in my code? My code looks like this:
function sendIcalEmail ($firstname, $lastname, $email, $meeting_date, $meeting_name, $meeting_duration) {
$from_name = “My Name”;
$from_address = “myname#mydomain.com”;
$subject = “Meeting Booking”; //Doubles as email subject and meeting subject in calendar
$meeting_description = “Here is a brief description of my meeting\n\n”;
$meeting_location = “My Office”; //Where will your meeting take place
//Convert MYSQL datetime and construct iCal start, end and issue dates
$meetingstamp = strtotime($meeting_date . ” UTC”);
$dtstart= gmdate(”Ymd\THis\Z”,$meetingstamp);
$dtend= gmdate(”Ymd\THis\Z”,$meetingstamp+$meeting_duration);
$todaystamp = gmdate(”Ymd\THis\Z”);
//Create unique identifier
$cal_uid = date(’Ymd’).’T’.date(’His’).”-”.rand().”#mydomain.com”;
//Create Mime Boundry
$mime_boundary = “—-Meeting Booking—-”.md5(time());
//Create Email Headers
$headers = “From: “.$from_name.” <”.$from_address.”>\n”;
$headers .= “Reply-To: “.$from_name.” <”.$from_address.”>\n”;
$headers .= “MIME-Version: 1.0\n”;
$headers .= “Content-Type: multipart/alternative; boundary=\”$mime_boundary\”\n”;
$headers .= “Content-class: urn:content-classes:calendarmessage\n”;
//Create Email Body (HTML)
$message .= “–$mime_boundary\n”;
$message .= “Content-Type: text/html; charset=UTF-8\n”;
$message .= “Content-Transfer-Encoding: 8bit\n\n”;
$message .= “<html>\n”;
$message .= “<body>\n”;
$message .= ‘<p>Dear ‘.$firstname.’ ‘.$lastname.’,</p>’;
$message .= ‘<p>Here is my HTML Email / Used for Meeting Description</p>’;
$message .= “</body>\n”;
$message .= “</html>\n”;
$message .= “–$mime_boundary\n”;
//Create ICAL Content (Google rfc 2445 for details and examples of usage, beware of adding tabs)
$ical = ‘BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:’.$from_address.’
DTSTART:’.$dtstart.’
DTEND:’.$dtend.’
LOCATION:’.$meeting_location.’
TRANSP:OPAQUE
SEQUENCE:0
UID:’.$cal_uid.’
DTSTAMP:’.$todaystamp.’
DESCRIPTION:’.$meeting_description.’
SUMMARY:’.$subject.’
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR’;
$message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n';
$message .= 'Content-Transfer-Encoding: 8bit\n\n';
$message .= $ical;
//SEND MAIL
$mail_sent = #mail( $email, $subject, $message, $headers );
if($mail_sent) {
return true;
} else {
return false;
}
}
Imho it is not or should not be possible to post an invite that automatically will be accepted. Instead you should inform your users that they can they can change their settings in Outlook to automatically accept (certain) invites.
Btw thanks for your snippet. Just what I needed.
Hi for calendar auto acceptance you should add the given lines in your code to create ics file.
ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName1 c;EMAIL=example1#mail.com:MAILTO:example1#mail.com
ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName2 c;EMAIL=example2#mail.comMAILTO:example2#mail.com

upload image in PHP5

I have this code in PHP to upload images to directory. The problem is: It's not uploading .png files.
Error: Você não enviou nenhum arquivo!
I don't know how to fix, already tried a lot of changes.
<?php
//Upload de arquivos
// verifica se foi enviado um arquivo
if(isset($_FILES['arquivo']['name']) && $_FILES["arquivo"]["error"] == 0)
{
echo "Você enviou o arquivo: <strong>" . $_FILES['arquivo']['name'] . "</strong><br />";
echo "Este arquivo é do tipo: <strong>" . $_FILES['arquivo']['type'] . "</strong><br />";
echo "Temporáriamente foi salvo em: <strong>" . $_FILES['arquivo']['tmp_name'] . "</strong><br />";
echo "Seu tamanho é: <strong>" . $_FILES['arquivo']['size'] . "</strong> Bytes<br /><br />";
$arquivo_tmp = $_FILES['arquivo']['tmp_name'];
$nome = $_FILES['arquivo']['name'];
// Pega a extensao
$extensao = strrchr($nome, '.');
// Converte a extensao para mimusculo
$extensao = strtolower($extensao);
// Somente imagens, .jpg;.jpeg;.gif;.png
// Aqui eu enfilero as extesões permitidas e separo por ';'
// Isso server apenas para eu poder pesquisar dentro desta String
if(strstr('.jpg;.png;.gif;.jpeg', $extensao))
{
// Cria um nome único para esta imagem
// Evita que duplique as imagens no servidor.
$novoNome = md5(microtime()) . $extensao;
// Concatena a pasta com o nome
$destino = 'images/uploads/logos/' . $novoNome;
// tenta mover o arquivo para o destino
if( #move_uploaded_file( $arquivo_tmp, $destino ))
{
echo "Arquivo salvo com sucesso em : <strong>" . $destino . "</strong><br />";
echo '<img src="' . $destino . '" />';
echo '<META http-equiv="refresh" content="0;URL=/administracao">';
exit;
}
else
echo "Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.<br />";
}
else
echo "Você poderá enviar apenas arquivos .jpg, .jpeg, .gif e .png.";
}
else
{
echo "Você não enviou nenhum arquivo!";
}
?>
Can someone help me please?
You are checking if the string after . matches your accepted extensions. Like I mentioned in the comment section a user can easily change their file's extension and upload it regardless of the content.
On PHP.net there is an article/comment about how to upload files, some safety issues are also explained briefly in code and solved. I think this part will do for you:
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.'); // You can replace this with a custom message if you want.
// Either that or catch it in higher level
}
Source to this code (PHP.net)
Also make sure that your errors are enabled, so you can spot any PHP mistakes:
error_reporting(E_ALL); // Report ALL errors once they occur
ini_set('display_errors', 1); // Once they get reported, print them as HTML on your page
One more suggestion, remove the error suppression # in the move_uploaded_file if statement. If anything fails, you won't see why.
So I think this saves you time, as well fixing your problem in a safe way.
Good luck.
some comments.
This path must have write permission.
$destino = 'images/uploads/logos/' . $novoNome;
Also check that your form has
enctype="multipart/form-data"

hotmail not receiving image attachment content

I'm trying to send a raw email with image attachments via AmazonSES using PHP. It works great when I send the email to a gmail account but hotmail accounts are receiving empty attached images. In other words, hotmail seems to recognize that there are attachments and these attachments have the correct name that i specified, it's just that they are always empty, sized 0 bytes. Googling is not helping... Thanks in advance!
$amazonSES = new AmazonSES();
// if (empty($attach)==0) {
// $response = $amazonSES->send_email(AWS_SES_FROM_EMAIL,
// array('ToAddresses' => array($to)),
// array('Subject.Data' => $subject,'Body.Text.Data' => $messagein,)
// );
// } else {
$rstring = 'ajfas90lsjhntlen89y34oi598';
$message= "To: ".$to."\n";
$message.= "From: " . AWS_SES_FROM_EMAIL . "\n";
$message.= "Subject: " . $subject . "\n";
$message.= "MIME-Version: 1.0\n";
$message.= 'Content-Type: multipart/mixed; boundary="ARandomString'.$rstring.'"';
$message.= "\n\n";
$message.= "--ARandomString$rstring\n";
$message.= 'Content-Type: text/plain; charset="utf-8"';
$message.= "\n";
$message.= "Content-Transfer-Encoding: 7bit\n";
$message.= "Content-Disposition: inline\n";
$message.= "\n";
$message.= $messagein;
$message.= "\n\n";
$message.= "--ARandomString$rstring\n";
foreach ($attach as $attachment) {
// $message.= "Content-ID: \<77987_SOME_WEIRD_TOKEN_BUT_UNIQUE_SO_SOMETIMES_A_#domain.com_IS_ADDED\>\n";
$message.= "Content-ID: \<". md5(uniqid(rand(), true)) ."#biomechanico.com\>\n";
$message.= 'Content-Type: application/zip; name="shell.zip"';
$message.= "\n";
$message.= "Content-Transfer-Encoding: base64\n";
$message.= 'Content-Disposition: attachment; filename="' . $attachment["name"] . '"';
$message.= "\n" . base64_encode(file_get_contents($attachment["file"])) . "\n";
$message.= "--ARandomString$rstring\n";
}
$response = $amazonSES->send_raw_email(array(
'Data'=> base64_encode($message)),
array('Source'=>AWS_SES_FROM_EMAIL, 'Destinations'=> $to));
You are producing a malformed message.
Consider using a proper library for generating mail messages, instead of stitching them together from raw strings.
Otherwise, here’s what I notice right away.
The final multipart boundary must be terminated by an extra --, i.e. the last line must be:
--ARandomStringajfas90lsjhntlen89y34oi598--
rather than
--ARandomStringajfas90lsjhntlen89y34oi598
In the attachment parts, you do not have a blank line between the Content-Disposition header line and the body.
Message lines must not be longer than 998 characters, but your Base64-encoded attachment data, however long, is always on a single line.
As far as I understand PHP, your syntax for Content-ID in the attachment parts is wrong, in that it produces Content-ID: \<whatever\> but should produce Content-ID: <whatever>
Lines must be terminated by CR LF (\r\n), but you have LF (\n).
A good way to debug message problems is to take the actual full generated message source ($message) and run it through Message Lint. If the above suggestions do not help, please post the generated message source rather than the PHP code.
For the Internet message format, please refer to RFC 5322. For the multipart message syntax, please refer to RFC 2046.

Cant send e-mail by php mail on first attempt

I'm trying to send an email via SMTP using PHPMailer on my site, it works the second time I try (use submit), but the first time it says it cannot authenticate, login or password is invalid. I have searched a lot and can't find the answer, can someone help me please?
By the way I'm using JSON to get the PHP response in an alert. My host doesn't have "smtp." in front because support told me to do it this way.
This is the code:
else {
$phpmail = new PHPMailer();
$phpmail->IsSMTP(); // envia por SMTP
$phpmail->Host = "velvetwebdesign.com.br"; // SMTP servers
$phpmail->Port = "587"; // Port
$phpmail->SMTPAuth = true; // Caso o servidor SMTP precise de autenticação
$phpmail->SMTPDebug = 1;
$phpmail->Username = "email#velvetwebdesign.com.br"; // SMTP username
$phpmail->Password = "xxxxxxx"; // SMTP password
$phpmail->IsHTML(true);
$phpmail->From = 'email#velvetwebdesign.com.br';
$phpmail->FromName = $_POST['nome'];
$phpmail->AddAddress("velvetwebdesign#velvetwebdesign.com.br");
$phpmail->AddAddress($_POST['email']);
$phpmail->Subject = 'Contato Velvet Web Design';
$phpmail->Body .= "<b>Cliente:</b> ".$_POST['nome']."<br />";
$phpmail->Body .= "<b>E-mail:</b> ".$_POST['email']."<br />";
$phpmail->Body .= "<b>Telefone:</b> ".$_POST['telefone']."<br />";
$phpmail->Body .= "<b>Assunto:</b> ".$_POST['assunto']."<br /><br />";
$phpmail->Body .= "<b>Mensagem:</b><br />".nl2br($_POST['mensagem'])."<br /><br />";
$phpmail->Body .= "Recebemos a sua mensagem, responderemos em breve.<br />";
$phpmail->Body .= "http://www.velvetwebdesign.com.br/";
$send = $phpmail->Send();
if($send){
echo "A Mensagem foi enviada com sucesso. Enviaremos uma copia para o seu e-mail tambem.";
exit;
}else{
echo "Tente novamente por favor. Erro: " .$phpmail->ErrorInfo;
exit;
}
}
?>

PHP Email Not Working

I've recently installed my server on VPS, PHP mail is not working, I've tryed everywhere but I can't get it to work. If it is not a syntax error I would appreciate if someone could help with setting PHP mail up. Im running ubuntu 10.04
My code is:
$ToEmail = 'my#email.com';
$EmailSubject = 'Site contact form ';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br>";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "Message: ".nl2br($_POST["message"])."<br>";
$MESSAGE_BODY .= "IP: ".$_SERVER['REMOTE_ADDR']";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
According to the log you posted:
Jun 13 11:49:42 hedgehog postfix/master[12617]: fatal: bind 0.0.0.0 port 25: Address already in use
This should give you a clue if you are unable to connect to your server.