Weird $_POST behavior in PHPMailer - php

I have a weird PHP issue. I'm using PHPMailer along with JQuery to itterate through a few email addresses and send them individually.
It works. BUT...PHPMailer raises an exception that sender is not found. I have tried var_dump(), and echoing the $_POST or $_GET for the sender email, and I get nothing. The other $_POST/$_GET show up just fine, just the email fails to show, even in the console.log.
Did I mention it works? That's the weird part; the script processes fine, and the emails are sent. I just get a PHPMailer exception and can't see the $_POST/$_GET variable.
Any help appreciated!
Here's is the JQuery -
// ------ Mail Send-Multi Button ------------
$(document).on('click','#send-multi',function(e){
e.preventDefault;
var subj = $('#subject').val();
var msg = $('#msg').val();
var i = 0;
$(".mailchek input:checkbox").each(function () {
if (this.checked) {
var sto = $(this).val();
//alert($(this).val());
i++;
//alert(i);
var itm = "sendto="+sto+"&subject="+subj+"&msg="+msg;
alert(itm);
//ajax for multi email
$.ajax({
type: "GET",
url: "webmail.php",
data: itm,
success: function(result){
//alert(result);
alert("test");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});//End AJAX
} //end Address loop
});
Here is the PHPMailer -
<?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 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Verbose debug off. Change to '2' for debug echo
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.somehost.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#somecompany.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('info#somecompany.com', 'Name');
$mail->addAddress($_GET[sendto]); // Add a recipient
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $_GET[subject];
$mail->Body = $_GET[msg];
$mail->send();
echo "here ".$send;
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>

Related

phpmailer attatch post data pdf file without save

hello im trying to send mail with input form javascript jspdf via phpmailer
mail sent ok but file were broken if i get $_POST['data'] through original php file.
how i can deliver jspdf file with $_POST['data'] to phpmailer?
i tried many ways but it didn't help much.
thank you for reading this
form_input.php
var create_pdf = document.getElementById("create_pdf");
create_pdf.addEventListener('click', function (event) {
html2canvas($('#pdf_wrap')[0] ,{
//logging : true,
//proxy: "html2canvasproxy.php",
allowTaint : true,
useCORS: true,
scale : 2
}).then(function(canvas) {
var imgData = canvas.toDataURL('image/jpeg');
var doc = new jsPDF("p", "px");
var options = {
pagesplit: true
};
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
//Send mail on other php
$.post("mail_send.php",
{
data: doc.output('datauristring')
}, function () {}).done(function() {/*SOME CODE*/});
// doc.save( 'file.pdf');
});
});
mail_send.php
require 'plugin/PHPMailer/class.phpmailer.php';
require 'plugin/PHPMailer/class.smtp.php';
require 'plugin/PHPMailer/PHPMailerAutoload.php';
if(!empty($_POST['data']))
{
echo $_POST['data'];
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = false; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.test.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'smtpid#dot.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // TCP port to connect to
$mail->SMTPSecure = 'ssl';
$mail->setFrom('setmail#mail.com', 'Mailer');
$mail->addAddress('user#mail.com', 'Joe User'); // Add a recipient
$mail->CharSet = "utf-8";
// ----------Attachments this doesn't work. delivered broken pdf file.
$base = explode('data:application/pdf;base64,', $_POST['data']);
$mail->addStringAttachment($base, 'pdfName.pdf');
// -----------
$mail->isHTML(true); // Set email format to HTML
$mail->Body = $body;
$mail->Subject = 'Here is the subject';
$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}";
}
You need to double check your data, but I think is the problem
$base = explode('data:application/pdf;base64,', $_POST['data']);
$mail->addStringAttachment($base, 'pdfName.pdf');
This will not result in a PDF attachment; it will result in a base64-encoded PDF attachment tagged as a PDF, which will then be base64-encoded a second time by PHPMailer because it can't know what data you are providing. So decode the PDF data before attaching it:
$mail->addStringAttachment(base64_decode($base), 'pdfName.pdf');

Problem with sending the response back to JS from PHP

I want to send to a mail with a click on the HTML. I used ajax to call a PHP file. I included the PHP mailer code to send an email. And I also include a print json_encode("Success") at the bottom. I couldn't send the success message from php back to JS. I have used Print and many other output commands in PHP its not working.
$.ajax({
url:"api/collect_money.php",
type:"POST",
data:ajax_data,
async:false,
success:function(response)
{
console.log(response,"hello");
}
});
This is my PHP:
function sendmail($bills_count_data)
{
//print_r($bills_count_data[0]['end_date']);
//Load Composer's autoloader
require 'php/vendor/phpmailer/phpmailer/src/Exception.php';
require 'php/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'php/vendor/phpmailer/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 = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '****#gmail.com'; // SMTP username
$mail->Password = '****'; // 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');
// Add a recipient
$mail->addAddress('****#gmail.com');
//$mail->addAddress('****#thewashhouseinc.com'); // Name is optional
// $mail->addReplyTo('info#example.com', 'Information');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
//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 = 'Collect Money Notification';
$mail->Body = "Collection has been made on ".$bills_count_data[0]['end_date']." The list of bills: one's ".$bills_count_data[0]['one']." two's ".$bills_count_data[0]['two']."";
$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;
}
}
sendmail($bills_count_data);
}
print ("success");
I don't see any response on the console. when I execute this code
This is likely to be your problem:
$mail->SMTPDebug = 2;
That outputs all kinds of stuff that's not remotely like JSON, and will cause your parsing of the response to fail. If you look at the raw response in your browser's dev tools, you should see it all. Disable debug output with:
$mail->SMTPDebug = false;

Why PHPMailer/Google SMTP Server is so slow

I am trying to create a simple contact form using PHPMailer and here is what i got so far:
contact.php:
<?php
require 'includes/config.php';
require 'includes/phpmailer/PHPMailerAutoload.php';
function sanitize($text) {
$text = trim($text);
if (get_magic_quotes_gpc()) {
$text = stripslashes($text);
}
$text = strip_tags($text);
return $text;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$entries = array();
$response = array();
// Escape and extract all the post values
foreach ($_POST as $key => $value) {
$entries[$key] = sanitize($value);
}
$name = $entries['cf_name'];
$email = $entries['cf_email'];
$message = $entries['cf_message'];
$subject = 'Contact form';
$replySubject = 'Contact form';
$mailBody = '<b>Email message</b>';
// Check is an AJAX request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// Create a new PHPMailer instance
$mail = new PHPMailer;
// Tell PHPMailer to use SMTP
$mail->isSMTP();
// Set the hostname of the mail server
$mail->Host = MAIL_HOST;
// Set the SMTP port number - 587 for authenticated TLS
$mail->Port = MAIL_PORT;
// 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
$mail->Username = MAIL_USER;
// Password to use for SMTP authentication
$mail->Password = MAIL_PASS;
// 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(MAIL_ADDR);
// Set the subject line
$mail->Subject = 'Formularz kontaktowy';
// Set email format to HTML
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
// HTML version
$mail->Body = $mailBody;
// Convert HTML into a basic plain-text alternative body
$mail->AltBody = strip_tags($mailBody);
// send the message
if ($mail->send()) {
$response['result'] = 1;
} else {
$response['result'] = 0;
$response['error'] = $mail->ErrorInfo;
}
echo json_encode($response);
} else {
header('Location: ' . BASE_URL);
exit();
}
} else {
header('Location: ' . BASE_URL);
exit();
}
config.php
<?php
define('BASE_URL', 'http://example.com');
define('MAIL_HOST', 'smtp.gmail.com');
define('MAIL_PORT', 587);
define('MAIL_USER', 'mygmailemail#gmail.com');
define('MAIL_PASS', 'mygmailpassword');
define('MAIL_ADDR', 'example#email.com');
Client-Side:
$('form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeArray();
var t1 = window.performance.now();
$.ajax({
type: 'POST',
url: this.action,
data: formData
})
.done(function(response) {
console.log('DONE', response);
var t2 = window.performance.now();
console.log('time', (t2 - t1) / 1000);
})
.fail(function(response) {
console.log('FAIL', response);
});
});
I am testing this code locally with EasyPHP Server. As you can see above i log time inside ajax done callback and the average time to send an email is 3-5 seconds which i found ridiculously slow. I am not PHP developer so I have no idea why is it so slow. Is it EasyPHP fault or something else I did wrong? Can you please tell how can I improve this code to send out emails faster?

PHPMailer Message could not be sent.Mailer Error: Message body empty

So this is my code, it seems like it doesn't catch my "content" input field which is not empty btw, however I get this error
Message could not be sent.Mailer Error: Message body empty
<?php
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'intrepid.servers.prgn.misp.co.uk'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'secret#secret.co'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
$mail->setFrom($_POST["userEmail"], $_POST["userName"]);
$mail->addAddress('myemailforreceivingemails#gmail.com'); // Add a recipient
$mail->addReplyTo($_POST["userEmail"], $_POST["userName"]);
if(is_array($_FILES)) {
$mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']);
}
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["content"];
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
This is from my index.php file
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
$.ajax({
url: "contact_mail.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#mail-status").html(data);
},
error: function(){}
});
}
}

SMTP Email is not sending on iPhone cordova WebApp, working in browser?

I have a little problem with an iOS cordova Webapp and PHP. The code below works perfectly on the computer(Xampp):
<?php
require 'lib/sendMail.php';
require '../php/PHPMailerAutoload.php';
$mail = new PHPMailer;
$sendMail = new sendMail();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'ex#ex.de';
$mail->Password = 'expw';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From = 'ex#ex.com';
$mail->FromName = 'Mailer';
$mail->addAddress($_POST['termin']['cityemail']);
$mail->isHTML(true);
$mail->Subject = 'ex';
$mail->Body = $sendMail->getMessage($_POST);
$mail->AltBody = $sendMail->getMessage($_POST);
if(!$mail->send()) {
print 'Message could not be sent.';
print 'Mailer Error: ' . $mail->ErrorInfo;
} else {
print 'Message has been sent';
}
?>
Note: I am using PhpMailer to send mails via the phone.
The problem is, that the phone is going crazy. Everything after "->" is ignored or something. This is how the screen looks after submitting the form:
How can this happen? The email is sending successfully on the browser.
The device is iPhone 5S 16GB with iOS 8.1.
Okay I've got a working solution. Simply put your php files on a server, make an ajax call with type = " post " and there you go. Example code below(I'm using jQuery validation plugin) :
$("#Formular").validate({
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax(
{
url : 'http://yoururl.de/file.php',
type: "POST",
data : dataString,
success:function(data, textStatus, jqXHR)
{
$('body').html(data);
}
});
},
rules: {
'phone': {
required: false,
phoneDE: true
}
},
messages: {
'phone': {
required: "Bitte gültige Telefonnummer eingeben"
}
}
});

Categories