PHP Mailer languages encoding issues: It accepts only English - php

I am using php mailer at my website contact form. When i receive a message in greek language, i don't receive the text as typed in the contact form. In class.phpmailer.php file line 59 the encoding is public $CharSet = 'iso-8859-1'; Is there a way to make my text appear correctly as typed in the contact form?
Languages comonly supported by ISO/IEC 8859-1 can be found here
I have also tried german and albanian languages but i also have the same problem. I can only receive english, if the user types another language on some words i receive "chinese".
I get this message:
The code:
<?php
require_once('phpmailer/class.phpmailer.php');
// if(isset($_POST['g-recaptcha-response'])){
if (empty($_POST['Email'])) {
$_POST['Email'] = "-";
}
if (empty($_POST['Name'])) {
$_POST['Name'] = "-";
}
if (empty($_POST['Subject'])) {
$_POST['Subject'] = " ";
}
if (empty($_POST['message'])) {
$_POST['message'] = "-";
}
$mymail = smtpmailer("example#gmail.com", $_POST['Email'], $_POST['Name'],
$_POST['Subject'], $_POST['message']);
function smtpmailer($to, $from, $from_name, $subject, $body)
{
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = 'example#gmail.com';
$mail->Password = 'pass';
$mail->SetFrom($from, $from_name);
$mail->Subject = " Contact form ~Name: $from_name ~ subject: $subject ";
$mail->Body = " You have received a new message
from $from_name, here are the details:\n\n_____
___________________\n" . "\nDear $from_name,\n
Your enquiry had been received on " . date("D j F ") . "
\nINFORMATION SUBMITTED: " . "\n\nName: $from_name\n\nEmail: $from
\nSubject: $subject\n\nMessage: $body \n\nTo:
$to\nDate: " . date("d/m/y") . "\nWebsite: " . "\n____________
__________________"; //end body
$mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Well done $from_name, your message has been sent!\n
We will reply to the following email: $from" . "\nYour Message: $body";
}
} //end function smtpmailer
//}
?>

In your example output, the char count amplification suggests that you're receiving data from your form in UTF-8, but are then telling PHPMailer (by default) that it's ISO-8859-1, which results in the kind of corruption you're seeing.
You should be using UTF-8 everywhere. In PHPMailer you do it like this:
$mail->CharSet = 'UTF-8';
Then you need to be sure that every step of your processing supports UTF-8 as well.

Related

The body of the form in Cyrillic outputs in my mail as strange symbols

First time using this platform, please be patient with me.
I have a contact form on my webpage. When I submit the message the body of the message that contains my Name, Phone, Subject, Message and Reply to appears in my mail as strange symbols.
I searched in the internet but the only thing found was:
'=?UTF-8?B?' . base64_encode("Съобщение от сайта: " . $subject) . '?=';
And it worked just for my subject. When I try to apply this for to my body, I get no success.
I will appreciate if someone can help me or give a direction how to fix this problem. Thank you in advance.
Enough said here is my code:
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "Грешка; трябва да изпратите формата";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$phone = $_POST['phone'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Име и имейл са задължителни.";
exit;
}
if(IsInjected($visitor_email))
{
echo "Невалиден имейл.";
exit;
}
$email_from = 'z3robot#...';//<== update the email address
$email_subject = '=?UTF-8?B?' . base64_encode("Съобщение от сайта: " . $subject) . '?='; "\n";
$email_body = "Name: $name. \n".
"Phone: $phone. \n".
"Subject: $subject. \n".
"The message is: $message. \n".
"Reply to: $visitor_email \n";
$to = "z3robot#...";//<== update the email address
$headers = "From: $email_from \r\n";
if(mail($to, $email_subject, $email_body, $headers)){
//if successful go to index page in 3 seconds.
echo "Съобщението е изпратено успешно. Ще бъдете прехвърлени на главната страница след 3 секунди.";
header("refresh:3; url=index.html");
}else{
//if not successful go to contacts page in 5 seconds.
echo "Съобщението НЕ е изпратено успешно. Ще бъдете прехвърлени отново в страница Контакти след 5 секунди.";
header("refresh:5; url=contact-us.html");
}
//done.
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}else{
return false;
}
}
?>
Thanks to all that make suggestions. I made a completely new file and used PHPMailer and everything works. Here is the code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Get data from form
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$phone = $_POST['phone'];
//Preparing mail content
$messagecontent = "Име: <br><b>$name</b>" .
"<br><br>Телефон: <br><b>$phone</b>" .
"<br><br>Основание: <br><b>$subject</b>" .
"<br><br>Съобщение: <br><b>$message</b>" .
"<br><br>Имейл: <br><b>$visitor_email </b><br>";
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8'; //to convert chars to Cyrillic alphabet
try {
//Line for debugging if needed
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Server settings
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mail.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'mail#mail.com'; //SMTP username
$mail->Password = 'password'; //SMTP password
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //SMTP Encryption
$mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom('mail#mail.com', 'Mailer'); //Add visitors email and name $$
$mail->addAddress('mail#mail.com', 'text'); //Add a recipient
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = "Съобщение от сайта: " . $subject; //subject of the send email
$mail->Body = $messagecontent; //Content message of the send email
$mail->send();
header("Location: sent.html");
}
catch (Exception $e)
{
header("Location: not-sent.html");
//echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

htmlentities ignores <br> when using PHPmailer

Some times ago I made a contact form to send email.
I had this:
If ($validity !='Good#Ripsi'){
$to = "contact-us#xx-xxxx.com";
$subject = "xx xxxx new Subscriber";
$email_address = htmlentities($_GET['email_address']);
$headers = "xxxxxxxxxx" . "\r\n" .
mail($to,$subject,$email_address,$headers);
header("Location: index.php");
}
And that worked fine. After I read that although I don't plan to send thousands of Newletters it would be better to use PHPmailer else it could be seen as spam and be blocked. I don't understand much about those mailing things. So I read a tutorial and it works just fine but for one thing: htmlentities doesn't do the job anymore and all <br> are ignored at reception.
I checked that : $mail->IsHTML(true);
Help would be greatly appreciated.
Here is the code using PHPMailer:
<?php
require "phpmailer/PHPMailer/PHPMailerAutoload.php";
define("DB_HOST","localhost");
define("DB_USERNAME","xxxx_xxxx");
define("DB_PASSWORD","xxxx");
define("DB_NAME","xxxxxx");
$conn = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die (mysqli-error());
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function smtpmailer($to, $from, $from_name, $subject, $body)
{
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'mail.xxxxx.com';
$mail->Port = 465;
$mail->Username = 'newsletter#xxxxx.com';
$mail->Password = 'xxxxxxx';
$mail->IsHTML(true);
$mail->From="newsletter#xxxx.com";
$mail->FromName=$from_name;
$mail->Sender=$from;
$mail->AddReplyTo($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send())
{
$error ="Error Ocured...";
return $error;
}
else
{
$error = "Please wait!! Your email is being sent... ";
return $error;
}
}
$from = 'newsletter#ts-ripsi.com';
$name = 'xxxxxxx T & S';
$subj = 'Newsletter from xxx and xxxx';
$msg = htmlentities($_GET['message']);
$sqli = "SELECT ID, Email FROM mailing_addresses";
$record = mysqli_query($conn, $sqli);
while ($row = mysqli_fetch_array($record)) {
$to = $row['Email'];
$error=smtpmailer($to,$from, $name ,$subj, $msg);
}
header("Location: index.php");
?>
I hadn't understood the use of IsHTML. In this case it had to be set to false.

PHP attach audio file in email

I'm using the following SMTP mail code to send audio attachment:
<?php
session_start();
$title = $_POST['title'];
$first_name = $_POST['name'];
$last_name = $_POST['lastname'];
$email_from = $_POST['email'];
$scaptcha = strtolower($_POST['scaptcha']);
if ($scaptcha != $_SESSION['captcha']) {
echo 'You have entered wrong captcha';
exit(0);
}
require('./class.phpmailer.php');
function clean_string($string) {
$bad = array("content-type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message = "";
$email_message .= "Title: " . clean_string($title) . "\n";
$email_message .= "First Name: " . clean_string($first_name) . "\n";
$email_message .= "Last Name: " . clean_string($last_name) . "\n";
$email_message .= "Email: " . clean_string($email_from) . "\n";
$allowedExts = array("mp3","wav","dss");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "audio/mpeg")) && in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "<script>alert('Error: " . $_FILES["file"]["error"] . "')</script>";
} else {
$d = 'Audio/Uploads/';
$de = $d . basename($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], $de);
$fileName = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
}
} else {
echo "<script>alert('Invalid file')</script>";
}
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "saro17.ams#gmail.com";
$mail->Password = "*****";
$mail->SetFrom($email_from, $first_name . ' ' . $last_name);
//$mail->AddReplyTo('replyto#example.com','First Last');
$mail->AddAddress('saro17.ams#gmail.com', 'Saravana');
$mail->Subject = 'New audio file received';
$mail->MsgHTML($email_message);
$mail->AltBody = 'This is a plain-text message body';
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
if (!$mail->Send()) {
echo "<script>alert('Mailer Error: " . $mail->ErrorInfo . "')</script>";
} else {
echo "<script>alert('Your request has been submitted. We will contact you soon.')</script>";
Header('Location: contact.php');
}
?>
Please help me to fix this. I have been trying this for more than a week. Still I didn't get it. I have tried the PHP mailer also. That also not working.
UPDATE: I'm getting the following error:
Mailer Error: The following From address failed: saro17.ams#gmail.com : Called MAIL FROM without being connected,
send the audio file link in message instead of inline attachment.
$mail->AddAttachment method use for inline attachment.
due to the file encryption and file size , maximum server not allow to send inline attachment of audio, video or zip files.
Well..It's really very easy to attach anything while using PHPMailer.Here is the code :
PHPMailer Link : https://github.com/PHPMailer/PHPMailer
You can add attachments like :
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
While here is full code :
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

Two versions of same email to two different recipients using class.phpmailer.php

I'm trying to send two versions of the same email to two recipients using phpMailer
Depending on the email I need to send one version or another.
At the moment I'm able to send only the same version to both email address
<?php
require_once('class.phpmailer.php');
if(isset($_POST['Submit'])) {
$fname = $_POST['fname'];
$maileremail = $_POST['maileremail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer();
$text = 'The person that contacted you is '.$fname.' E-mail: '.$maileremail.' Subject: '.$subject.' Message: '.$message.' :';
$body = eregi_replace("[\]",'',$text);
$text2 = 'The person that contacted you is '.$fname.' E-mail: REMOVED - To get email address you must login Subject: '.$subject.' Message: '.$message.' :';
$body2 = eregi_replace("[\]",'',$text2);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "xxxxx.xxxxx.xxx"; // SMTP server
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "xxxxx.xxxxx.xxx"; // sets the SMTP server
$mail->Port = XXXXXXXX; // set the SMTP port for the GMAIL server
$mail->Username = "xxxxx#xxxxx.xxx"; // SMTP account username
$mail->Password = "XXXXXXXX"; // SMTP account password
$mail->SetFrom('xxxxx#xxxxx.xxx', 'XXXXXXXX');
$mail->Subject = $subject;
$add = array("first#email.xxx", "second#email.xxx");
foreach($add as $address) {
if($address == "first#email.xxx") {
$mail->AddAddress($address, "xxxxxxxxx");
$mail->Body = $body;
}
elseif($address == "second#email.xxx") {
$mail->AddAddress($address, "xxxxxxxxx");
$mail->Body = $body2;
}
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "<h3><b>Message sent!</b></h3>";
}}?>
If you're looking to do all the setup once for minimal repetition, simply clone your $mail object in your foreach($add) loop:
foreach ( $add as $address ) {
$current = clone $mail;
if ( $address == 'first#mail.com' ) {
$current->AddAddress($address, "xxxxxxxxx");
$current->Body = $body;
$current->send();
} elseif....
This creates a separate clone of your $mail object for every loop, allowing you to add different email bodies, subjects, etc. without having to rewrite all connection settings.
I think you want to seach the $maileremail inside $add and send the desired email.
$add = array("first#email.xxx", "second#email.xxx");
$mail->AddAddress($maileremail, "xxxxxxxxx");
if($maileremail === $add[0])
$mail->Body = $body;
if($maileremail === $add[1])
$mail->Body = $body2;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "<h3><b>Message sent!</b></h3>";
}
EDITED:
I misunderstood the question. Brian is right.

PHPMailer error(s)

function register_contact ($person = array()) {
$nogood = false;
foreach ($person as $val) {
if (strlen($val)==0) {
$nogood = true;
$status = "There was an error sending the registration please fill in all fields";
}
}
if (!$nogood) {
require_once("class.phpmailer.php");
$message = "New request for Fox In Touch Recipient:.\r\n\r\n";
$message .= "Forename: " . $person['fname'];
$message .= "\r\nSurname: " . $person['sname'];
$message .= "\r\nEmail: " . $person['email'];
$message .= "\r\nJob Title: " . $person['job'];
$message .= "\r\nCompany: " . $person['company'];
$message .= "\r\n\r\nFox In Touch.";
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "ahost"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "name"; // SMTP username
$mail->Password = "pass"; // SMTP password
//$mail->Post = 587;
$mail->From = "foxintouch#bionic-comms.co.uk";
$mail->FromName = "Fox In Touch";
//$mail->AddAddress("foxlicensing.europe#fox.com", "Fox Licensing");
$mail->AddAddress("andrew#yahoo.co.uk", "Andrew");
$mail->AddReplyTo("foxintouch#bionic-comms.co.uk","Information");
$mail->IsHTML(false); // send as HTML
$mail->Subject = "Contact request for Fox In Touch!";
$mail->Body = $message;
if(!$mail->Send()) {
$nogood = true;
$status = "Message was not sent <p>";
$status .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$status = "Thank you! Your message has been sent to 20th Century Fox. Submit another?";
}
}
return array('email_failed'=>$nogood, 'status'=>$status);
}
The above code keeps giving me the error, "Mailer Error: Language string failed to load: recipients_failedandrew#yahoo.co.uk". I have tried changing the AddAddress(). The smtp connection settings are correct, as this was the last error i had! Any help would be much appreciated. Thanks
It sounds like you have two problems.
1) Your language file isn't being loaded - see installation
2) The recipient is being rejected - errr double check the SMTP settings and the recipient address

Categories