Having some trouble sending properly formatted HTML e-mail from a PHP script. I am running PHP 5.3.0 and Apache 2.2.11 on Windows XP Professional.
The output looks like this:
Agent Summary for Support on Tuesday April 20 2010=20
Ext. Name Time Volume
137 Agent Name 01:27:25 1
138 =09 00:00:00 0
139 =09 00:00:00 0
You see the =20 and =09 in there? If you look at the HTML you also see = signs being turned into =3D. I figure this is a character encoding issue as I read the following at Wikipedia:
ISO-8859-1 and Windows-1252 confusion
It is very common to mislabel text data with the charset label ISO-8859-1, even though the data is really Windows-1252 encoded. In Windows-1252, codes between 0x80 and 0x9F are used for letters and punctuation, whereas they are control codes in ISO-8859-1. Many web browsers and e-mail clients will interpret ISO-8859-1 control codes as Windows-1252 characters in order to accommodate such mislabeling but it is not standard behaviour and care should be taken to avoid generating these characters in ISO-8859-1 labeled content.
This looks like the problem but I don't know how to fix. My code looks like this:
ob_start();
report_queue_summary($yesterday,$yesterday,$first_extension,$last_extension,$queue);
$body_report = ob_get_contents();
ob_end_clean();
$body_footer = "This is an automatically generated e-mail.";
$message = new Mail_mime();
$html = $body_header.$body_report.$body_footer;
$message->setHTMLBody($html);
$body = $message->get();
$extraheaders = array("From"=>"***redacted***","To"=>$recipient, "Subject"=>"Agent Summary for $yesterday [$queue]", "Content-type"=>"text/html; charset=iso-8859-1");
$headers = $message->headers($extraheaders);
# setup e-mail;
$host = "*********";
$port = "26";
$username = "*****";
$password = "*****";
# Send e-mail
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($recipient, $extraheaders, $body);
if (PEAR::isError($mail)) {
echo("" . $mail->getMessage() . "");
} else {
echo("Message successfully sent!");
}
Is the problem that I'm using output buffering?
The problem is that you need the following header:
Content-Transfer-Encoding: quoted-printable
Related
I'm setup a PHPMailer PHP Form that send us the form to our Office 365 account. Im having issue with French accents displayed has "ééé à à à çç" accents like "éé àà çç".
PHP Form are encoded in UTF-8;
PHP Code are also encoded in UTF-8;
But the email received seems to not show the proper characters.
I have add theses settings and nothing has changed :
In the PHP file
header('Content-Type: charset=utf-8');
Also
$mail->isHTML(true); // Set email format to HTML
$mail->CharSet = "UTF-8";
Php Sending Form Source Code:
<?php
header('Content-Type: charset=utf-8');
ini_set('startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php/phpmailer/vendor/phpmailer/phpmailer/src/Exception.php';
require 'php/phpmailer/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'php/phpmailer/vendor/phpmailer/phpmailer/src/SMTP.php';
$nom_compagnie = $_POST['nom_compagnie'];
$nom_complet = $_POST['nom_complet'];
$poste = $_POST['poste'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$commentaire = $_POST['commentaire'];
$from = $_POST['email'];
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'PrivateKey',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the reCAPTCHA is not properly set up
echo 'reCAPTCHA error: Check to make sure your keys match the registered domain and are in the correct locations. You may also want to doublecheck your code for typos or syntax errors.';
} else {
// If CAPTCHA is successful...
try {
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'EmailAccount';
$mail->Password = 'Password';
$mail->addReplyTo($from, $nom_complet);
$mail->SetFrom ("Hidden", "Hidden");
$mail->addCC ("Hidden", "Hidden");
$mail->addAddress ('Hidden', 'Hidden);
//$mail->SMTPDebug = 3;
//$mail->Debutoutput = fonction($str, $level) {echo "debug level $level; message: $str";}; //
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "FORMULAIRE CONTACT";
$mail->Body = "
<html>
<head>
<meta charset=\"UTF-8\">
<title>Formulaire de Contact</title>
....
</html>";
$mail->AltBody = "";
$mail->CharSet = "UTF-8";
//$mail->msgHTML(file_get_contents('email_form_contact-fr.html'));
$mail->send();
// Paste mail function or whatever else you want to happen here!
} catch (Exception $e) {
echo $e->getMessage();
die(0);
}
header('Location: envoi_form_contact-success-fr.html');
}
?>
The email received has shown like this :
The H3 title in the email are shown
Vous avez reçu un formulaire de contact via le site Web
It supposed to be written like this
Vous avez reçu un formulaire de contact via le site web
Accent "é" are also displayed has "é".
I don't know where is the problem.
Any clue if my code are well programmed?
Thanks.
Replace
$mail -> charSet = "UTF-8";
with
$mail->CharSet = 'UTF-8';
Bonjour Stéphane. This page describes the symptom you are seeing; one character turning into two means that your data is in UTF-8, but is being displayed using an 8-bit character set. Generally speaking, PHPMailer gets this right, so you need to figure out where you are going wrong.
If you use SMTPDebug = 2 you will be able to see the message being sent (use a really short message body like é😎 that is guaranteed to only work in UTF-8).
Make sure that the encoding of the script file itself is also UTF-8 - putting an emoji in it is a good way of being sure that it is.
The problem with diagnosing this is that you'll find your OS interferes - things like copying to the clipboard are likely to alter encodings - so the way to deal with it is to use a hex dump function that lets you inspect the actual byte values. French is one of the easier ones to look at because nearly all characters will be regular single-byte ASCII-compatible characters, and accented characters will be easier to spot. In PHP the bin2hex() function will do this.
You have 2 typos: Debutoutput should be Debugoutput and fonction should be function - and that is a good place to dump hex data from:
$mail->Debugoutput = function($str, $level) {echo $str, "\n", bin2hex($str), "\n";};
Here's an example:
echo 'abc ', bin2hex('abc');
which will produce abc 616263; each input char results in 2 hex digits (1 byte) of output. If your input is abé and your charset is ISO-8859-1, it will come out as abé 6162e9, because é in that charset is e9 (in hex). The same string in UTF-8 would come out as abé 6162c3a9, because é in UTF8 is c3a9 - two bytes, not just one. Inspecting the characters like this allows you to be absolutely certain what character set the data is in - just looking at it is not good enough!
So, while I can't tell exactly where your problem is, hopefully you have some better ideas of how to diagnose it.
Alrighty, I've been beating my head against this one for a few days and after extensive Googling (there's a lot of purple links when I search anything regarding this now) I'm pretty much stumped. The form works both from our domain and the AMP one, so maybe I should just get over it and let it be. At the same time though, I want it to be correct so hopefully someone can help me out here.
I have read the AMP CORS documentation a few times and everything seems all good to me.
On form submission, all of our forms return the error below. Visually the URL's appear the same. I've pasted them into a plain text editor and all seems good there too.
As a result of this error our forms technically throw an error message on submit. We have just flipped the messages around for now so an error pops up as a success, which is probably not the greatest as if it should properly succeed it will throw an error message.
We are running the headers out of our htaccess file, code below for that.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Credentials "true"
#Header set Access-Control-Allow-Origin "static.craigmanufacturing.com"
#Header set Access-Control-Allow-Origin "https://www-craigattachments-com.cdn.ampproject.org"
#Header set Access-Control-Allow-Origin "https://www-craigattachments-com.amp.cloudflare.com"
SetEnvIf Origin "https://(static.craigmanufacturing.com|www-craigattachments-com.cdn.ampproject.org|www-craigattachments-com.amp.cloudflare.com|https://cdn.ampproject.org)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Source-Origin "https://www.craigattachments.com"
Header set Access-Control-Expose-Headers AMP-Access-Control-Allow-Source-Origin
Header set AMP-Access-Control-Allow-Source-Origin "https://www.craigattachments.com"
</IfModule>
Anyone have any thoughts on why we may be getting this error that I may be missing? You can try out our contact form here: https://www.craigattachments.com/contact-us - all messages go to an inbox that only I have access to so no worries on hitting it.
I will happily provide more details on this if required as I'm sure I may have forgotten to include some crucial detail as my brain is mush about this issue at this point.
Edit: here's the PHP (stripped down a bit of my details and the HTML) behind sending the form as well. Doubled up on headers in here because otherwise it seems to throw a JSON syntax error, even though after testing the error above is coming from the htaccess file. I have also tried stripping the headers from htaccess and including them in the PHP only.
<?php
header("Access-Control-Allow-Headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("Access-Control-Allow-Methods:POST, GET, OPTIONS");
header("Access-Control-Allow-Origin:".$_SERVER['HTTP_ORIGIN']);
header("Access-Control-Expose-Headers:AMP-Access-Control-Allow-Source-Origin");
//header("AMP-Access-Control-Allow-Source-Origin:https://".$_SERVER['HTTP_HOST']);
//header("AMP-Access-Control-Allow-Srouce-Origin:https://www.craigattachments.com");
header("AMP-Access-Control-Allow-Source-Origin:".$_REQUEST['__amp_source_origin']);
header("Content-Type: application/json");
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT);
set_include_path("." . PATH_SEPARATOR . ($UserDir = dirname($_SERVER['DOCUMENT_ROOT'])) . "/pear/share/pear" . PATH_SEPARATOR . get_include_path());
require_once "Mail.php";
require_once "Mail/mime.php";
$host = "###";
$username = "###";
$password = "###";
$port = "###";
$to = "###";
$email_from = "###";
$email_name = $_POST['fullname'];
$email_subject = $_POST['subject'];
$email_body = $_POST['message'];
$email_address = $_POST['sender_email'];
?>
<?php
$html_email = '';
$crlf = "\n";
echo json_encode(array($email_subject, $email_address, $html_email, $email_name));
$headers = array ('From' => $email_name . "<" . $email_from . ">", 'To' => $to, 'Subject' => $email_subject, 'Reply-To' => $email_address);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mime = new Mail_mime($crlf);
$mime->setHTMLBody($html_email);
$html_email = $mime->get();
$headers = $mime->headers($headers);
list($user,$domain) = explode('#', $email_address);
$mail = $smtp->send($to, $headers, $html_email);
?>
Edit2: I updated my code to include my commented out other attempts.
This header allows the specified source-origin to read the authorization response. The source-origin is the value specified and verified in the "__amp_source_origin" URL parameter (for example, "https://publisher1.com").
The value needs to be an allowed origin, not a comma-separated list of allowed origins which is what you are providing.
Problem with sending Cyrillic Email with PHP.
My side:
Server IIS - Database MsSQL - email server: Exchange 2010 /communication via PHP EWS/
Reciever is UA Goverment owned company with their specific software for receiving emails. It is working with MS Outlook /manually send/.
I tried send it as text /not html/ or i tried PHP Mailer, i also already tried with C# /all are not working with this specific company /on gmail or hotmail it's working fine//.
$ews = new ExchangeWebServices($server, $username, $password);
$msg = new EWSType_MessageType();
$toAddresses = array();
$toAddresses[0] = new EWSType_EmailAddressType();
$toAddresses[0]->EmailAddress =;
$toAddresses[0]->Name =;
$msg->ToRecipients = $toAddresses;
$fromAddress = new EWSType_EmailAddressType();
$fromAddress->EmailAddress =;
$fromAddress->Name =;
$msg->From = new EWSType_SingleRecipientType();
$msg->From->Mailbox = $fromAddress;
$msg->Subject = "Test";
$msg->Body = new EWSType_BodyType();
$msg->Body->BodyType = 'HTML'; //Text HTML
$msg->Body->_ = $UAText;
$msgRequest = new EWSType_CreateItemType();
$msgRequest->Items = new EWSType_NonEmptyArrayOfAllItemsType();
$msgRequest->Items->Message = $msg;
$msgRequest->MessageDisposition = 'SendAndSaveCopy';
$msgRequest->MessageDispositionSpecified = true;
$response = $ews->CreateItem($msgRequest);
var_dump($response);
Thank You,
If its working with an normal Outlook client, however not with your solution my first check would be to compare the header from two example emails (one from outlook and one from your solution). I think that the content-type is set correctly with Outlook however not with your solution.
So you might wish to set the content encoding to UTF-8 in your solution. So I assume the content inside $UAText is some HTML stuff. You might therefore wish to flag that part as UTF-8 via:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and see how it works.
Additional you might wish to set the encoding directly inside your code via:
$ews = new ExchangeWebServices($host, $user, $password, ExchangeWebServices::VERSION_2007_SP1);
$msg = new EWSType_MessageType();
$msg->MimeContent = new EWSType_MimeContentType();
$msg->MimeContent->_ = base64_encode("Mime-Version: 1.0\r\n"
. "From: michael#contoso.com\r\n"
. "To: amy#contoso.com\r\n"
. "Subject: nothing\r\n"
. "Date: Tue, 15 Feb 2011 22:06:21 -0000\r\n"
. "Message-ID: <{0}>\r\n"
. "X-Experimental: some value\r\n"
. "\r\n"
. "I have nothing further to say.\r\n");
$msg->MimeContent->CharacterSet = 'UTF-8';
Note: Here is a good starting point regarding the content-type encoding option. You also might wish to check the official Microsoft howto here.
I am using the PHP imap functions to read a mailbox that receives UTF-8 encoded plain text email (generated by another server). Accented characters are replaced with question mark (?). Below is my code and following that are two attempts at fixing it. How do I fix the problem? I have no control over the server that generates the messages, but they claim they are encoded UTF-8. mb_detect_encoding says the imap_body function is returning an ASCII string, but I've found mb_detect_encoding to be somewhat buggy in the past.
$connection = imap_open( '{localhost:993/ssl/novalidate-cert}INBOX', 'xxxxxxx', 'xxxxxxx', 0, 1 );
$result = imap_search( $connection, 'UNSEEN' );
if ( $result )
{
foreach ( $result as $msgno )
{
$body = imap_body( $connection, $msgno );
// ... (code to process the message) ...
imap_mail_move( $connection, "$msgno:$msgno", 'INBOX.processed' );
}
imap_expunge( $connection );
imap_close( $connection );
}
}
I tried the following to convert to UTF-8, even though the message was already UTF-8:
$current_encoding = mb_detect_encoding( $body, 'auto' ); // Returns "ASCII"
$body = mb_convert_encoding( $body, $current_encoding, 'UTF-8' );
I also tried:
$body = mb_convert_encoding( $body, 'UTF-8', 'UTF-8' );
After getting the body of the email
$body = imap_body( $connection, $msgno );
Decode the Message Body by using code below
$body = utf8_decode(imap_utf8($body));
Use the same logic for $subject also..
For more details Refer imap_utf8
Here is the solution: I got hold of the people generating the email and they made the following header changes:
Content-type: text/html; charset=UTF-8
Content-transfer-encoding: quoted-printable
That solved it. My PHP program now sees the UTF-8 characters.
I've found and tried various solutions given in other questions about utf-encoding for special characters and other related problems, but without any success.
I have an html contact form that sends information to my mail address with a simple php script using PEAR Mail mime. I can send information containing special characters from my test site on localhost with no problems, but not after I uploaded to my server.
eg message:
Test special characters: é è ç à ô
after being sent from server becomes:
Test special characters: é è ç à ô
I am guessing it's an encoding problem from my web server, but am kinda stuck at how to resolve the problem.
The meta tags in file containing the form are set to:
<meta charset="utf-8">
and the form is specified to accept charset utf-8:
<form name="contact" method="post" action="assets/send_form.php" accept-charset="UTF-8">
I've also tried sending content from php file with:
header("Content-Type: text/html; charset= UTF-8");
as well as creating $headers for the message with 'Content-Type' = 'text/html; charset="UTF-8".
The relevant php code in my script:
//This section creates the email headers
$headerss=array();
$headerss['From']= $from_address;
$headerss['To']= $siteEmail;
$headerss['Subject']= $email_subject;
$headerss['Return-Path']= $contactEmail;
$headerss['Date']= date("r");
$headerss['Content-Type'] = 'text/html; charset="UTF-8"';
// This section creates the smtp inputs
$auth = array('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password);
// create new Mail_mime instance, set utf-8 charset
$mail = new Mail_mime();
$mail -> setHTMLBody($email_message);
//CHECK THIS OUT FOR UTF-8 *****************************
$mimeparams=array();
$mimeparams['text_encoding']="7bit";
$mimeparams['text_charset']="UTF-8";
$mimeparams['html_charset']="UTF-8";
$mimeparams['head_charset']="UTF-8";
$mimeparams['eol']= "\n" ;
$body = $mail->get($mimeparams);
$headers = $mail->headers($headerss);
// This section send the email
$smtp = Mail::factory('smtp', $auth);
$sendmail = $smtp->send($siteEmail, $headers, $body);
Any help will be really appreciated. Thanks.
Try to put before
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
I experienced the same problem and my solution was to save the php file in same format, in UTF-8 as I had saved in ANSI format. That solved my problem anyway.