PHPMailer doesn't show HTML - php

I am building a bulk email tool to address a list of our clients regarding some upcoming migrations. Our current mass mail tool doesn't quite cut it in this particular case, where I have opted to just build one instead.
I am using TinyMCE to provide an editor for the email message body and passing this along to PHPMailer to send out. Everything is working great except the html is not displayed properly when viewed in a client such as Outlook. I have made absolutely sure $mail->isHTML(true) is set so I am at a loss now.
I echo out the value of $message in the bulk_mail_sender() function and its correct. If I paste this string as $mail->Body it works. If I have $message set as $mail->Body however, it turns into all sorts of strange characters.
Message Source:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><p>Hi there,</p>
<p>Â </p>
<p>What is up foo</p>
Code:
function bulk_mail_sender($vars, $emails, $subject, $message)
{
foreach ($emails as $email)
{
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}
}
}
function bulk_mail_output($vars)
{
if (!empty($_POST))
{
$subject = $_POST['subject'];
$message = $_POST['message'];
$emails = $_POST['emails'];
$emails = explode(PHP_EOL, $emails);
bulk_mail_sender($vars, $emails, $subject, $message);
}
else
{
echo '<form method="POST" action="">';
echo 'Subject: <input type="text" name="subject" id="subject"></br></br>';
echo '<textarea rows="10" cols="100" name="message" id="message"></textarea></br></br>';
echo '<h3>Email Addresses</h3>';
echo '<textarea rows="10" cols="100" name="emails" id="emails"></textarea></br></br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
echo '<script language="javascript" type="text/javascript" src="../includes/jscript/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode: "exact",
elements: "message",
theme: "advanced",
entity_encoding: "raw",
convert_urls: false,
relative_urls: false,
plugins: "style,table,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,visualchars,xhtmlxtras",
theme_advanced_buttons1: "cut,copy,paste,pastetext,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,search,replace",
theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,cleanup,code,help",
theme_advanced_buttons3: "", // tablecontrols
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
});
function toggleEditor(id)
{
if (!tinyMCE.get(id))
tinyMCE.execCommand(\'mceAddControl\', false, id);
else
tinyMCE.execCommand(\'mceRemoveControl\', false, id);
}
</script>';
}
}

While I couldn't ever find a way to fix this within TinyMCE, the workaround used was to just wrap my $message variable in the html_entity_decode function when setting it to the mail body. I would have preferred to pass the data from TinyMCE properly the first time, however the entity encoding cannot be fully disabled for some reason.
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = html_entity_decode($message);
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}

Related

PHPMailer 6 Contact Form with Gmail SMTP

I'm trying to make it so that emails can be sent to my Gmail address rather than my domain name email using a PHPMailer form that is in a Bootstrap website. That is my main goal, and the other is to figure out how to have the form include the person's name, email and a subject populate the email rather than the set subject and "no-reply" email. Any help I could get on this would be great; I thought I would see if anyone wanted to solve this for the community here before I hire a freelancer. Thanks!!
I've tried several tutorials to solve this as well as trying to combine the existing code I'm posting below with the SMTP Gmail version on the PHPMailer Github page ( https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps )but I was not successful, I would instead post the working code here to my domain name email than my failed attempts at sending to Gmail.
<form id="contact-form" method="post" action="contact.php">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">
</div>
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">
</div>
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>
</div>
<input type="submit" class="btn btn-outline-light btn-sm" value="Send message">
</div>
</form>
<?php
use PHPMailer\PHPMailer\PHPMailer;
require './PHPMailer-master/vendor/autoload.php';
$fromEmail = 'noreply#email.com';
$fromName = 'No Reply Email';
$sendToEmail = 'name#mydomain.com';
$sendToName = 'New Website Email Message';
$subject = 'New message from contact form';
$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');
$okMessage = 'Successfully submitted - we will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml .= "<h3>New message from website:</h3><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a great day!</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName);
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->Subject = $subject;
$mail->Body = $emailTextHtml;
$mail->isHTML(true);
if(!$mail->send()) {
throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
It is working on my projects. You can also remove the part of the code which you don't need like attachments. One more thing if you want to hide the debugging code errors and notifications remove or comment this line $mail->SMTPDebug = 2.
Check this similar StackOverflow article for more help
If you still need more help to let me know.
Hope this may help you.
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // 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
//Recipients
$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');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$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';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}`enter code here`
s
This is what I use for my form mail, change the variables accordingly.
// PHPMailer
require '/var/www/...../PHPMailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "abcdefgh#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "pppppppppppppppp";
//Set who the message is to be sent from
$mail->setFrom($Email, $Name);
//Set an alternative reply-to address
$mail->addReplyTo($Email, $Name);
//Set who the message is to be sent to
$mail->addAddress('myemailaddress#gmail.com', 'Form Mail');
//Set the subject line
$mail->Subject = 'Form Mail";
// END PHP Mailer
$mail->ContentType = 'text/plain';
$mail->isHTML(false);
// $mail->msgHTML("$Message");
$mail->Body = $Message;
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Thank you for sending your message.";
}

PHPMailer email not send and not get any error

The below function to send email but got any mail or error :
function send_Email($email, $subject, $body ,$cc = '')
{
$this->Log("Sending email with To: ". $email. " <br>Subject: ". $subject ." <br>Body: ".$body);
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->IsSMTP();
$mail->CharSet = "utf-8";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = email_host;
$mail->Username = email_username;
$mail->Password = email_password;
$mail->SetFrom('support#xyv.com', 'zzz Support');
$mail->AddReplyTo('support#xyv.com', 'zzz Support');
$mail->AddAddress($email);
$mail->AddBCC('support#xyv.com');
$mail->AddBCC('zzz#zzz.com');
if(!empty($cc)) {
$mail->addCC($cc);
}
$mail->Subject = $subject;
$mail->Body = $body;
echo "<pre>"; print_r($mail);echo "</pre>";
$response = $mail->Send();
var_dump($response);
return $response;
}
Debug : IN DEBUG MODE NOT GET ERROR
[error_count:protected] => 0
It would really help to read the docs and base your code on the examples provided, which show how to get info about errors, and show debug output. You're not getting any output because you're not asking for any. From the example in the readme:
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
That will show you the reason for any sending failure. To enable SMTP debug output, do this:
$mail->SMTPDebug = 2;

$.post to phpMailer failed

I'm using $.post in my js to check my form and if all is okay, the data will go to my sendinquiry.php which will send the contact form email. All is working just that I can't catch the echo "submitted" to sdata so that I can display the thank you message in jQuery. Anyone?
jQuery
.
.
.
if(errflag > 0){
$('.disclaimer').addClass('errortext');
}
else {
$.post(
"sendinquiry.php",
$('#contact_form').serialize(),
function(sdata)
{
if(sdata == 'submitted') {
var ntext = '<div class="row topbot_m shortwidth"><div class="columns medium-12 text-center"><h3>THANK YOU FOR SUBMITTING YOUR ENQUIRY.</h3><p>Our Sales Representative will contact you shortly.</p></div></div>';
$('#contact_form').hide().html(ntext).fadeIn('slow');
}
}
);
}
PHP
<?php
$subject = "Line Enquiry Form";
$gname = "High Line";
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$contactno = $_POST['contactno'];
$emailadd = $_POST['emailadd'];
$fmessage = $_POST['message'];
require 'PHPMailermaster/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxx'; // SMTP username
$mail->Password = 'xxx'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom($emailadd, $fname);
$mail->addAddress('sender#gmail.com', 'Reza San'); // Add a recipient
$mail->addReplyTo($emailadd, $fname +' '+$lname);
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body ="<html>
<head>
<title>".$gname."</title>
</head>
<body>
<h2>".$subject."</h2>
<table>
<tr><td width='200'>First Name: </td><td>".$fname."</td></tr>
<tr><td width='200'>Last Name: </td><td>".$lname."</td></tr>
<tr><td width='200'>Contact No: </td><td>".$contactno."</td></tr>
<tr><td width='200'>Email Address: </td><td>".$emailadd."</td></tr>
<tr><td width='200'>Message: </td><td>".$fmessage."</td></tr>
</table>
</body>
</html>";
if($mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'submitted';
}
?>

PHPmailer how to show message

How I can show success message after to click send in my form? my phpmailer is working but I want to also after to click send to redirect to my homepage (index.html) and show my message div. This is my php code.
<?php
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$subject = $_POST['subject'];
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.xxxxxxx.pl'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'xxxxx#xxxxxxxx.pl'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom($email, $name);
$mail->addAddress('xxxx#gmail.com', 'xxxxxxxx'); // Add a recipient // Name is optional
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = 'Body test';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
header('Location: index.html');
}
And this is my Jquery code to show/hidden div succes:
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
You could send extra parameter with your request :
header('Location: index.php?r=1');
Then in your index page get the parameter and use it to show the box :
<script>
var result="<?php echo $_GET['r']; ?>";
if(parseInt(result)){
$('.box-up').animate({top : 150}, 'normal').delay(3000).animate({top : -500}, 'normal');
}
</script>
Hope this helps.

attachment is not sent with phpmailer

I'm trying to send an attachment with the phpMailer script.
Everything is working correctly since my email is sent correctly, however I do have a problem with an attachment that is not sent.
HTML part:
<p>
<label>Attachment :</label>
<input name="doc" type="file">
</p>
PHP:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["name"];
$mail->FromName = 'Your Name';
$mail->Subject = 'Message Subject';
$mail->addAddress('*****');
$mail->addAttachment($_FILES["doc"]);
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = "You got a new message from your website :
Name: $_POST[name]
Company: $_POST[company]
Phone: $_POST[phone]
Email: $_POST[email]
Message: $_POST[message]";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<p> <img src="img/correct.png" alt="icon" style=" margin-right: 10px;">Thank you! We will get back to you soon.</p>
</body>
</html>
Try:
if (isset($_FILES['doc']) &&
$_FILES['doc']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['doc']['tmp_name'],
$_FILES['doc']['name']);
}
Basic example can also be found [here](https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/AdvancedMail).
The function definition for `AddAttachment` is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
Please have a look about how PHP file uploads work. This array key:
$_FILES["doc"]
... will never contain a file. At most, it'll contain an array with information about where to find the file.
Untested solution, but should work:
change
$mail->addAttachment($_FILES["doc"]);
to
$mail->addAttachment($_FILES["doc"]["tmp_name"], $_FILES["doc"]["name"], "base64", $_FILES["doc"]["tmp_type"]);
However, please consider learning php upload file handling as already commented by others. Don't use user input without validation. Never!

Categories