phpmailer attatch post data pdf file without save - php

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');

Related

Phpmailer send attachments as plain text

When I use phpmailer to send four pdf attachments, one is sent as pdf and three of them as plain text. Like this is sent only on macbook app mail. On gamil sent all 4 attachments well.
enter image description here
enter code here
$mail = new PHPMailer(true);
try {
$mail->CharSet = 'UTF-8';
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '***************'; // SMTP username
$mail->Password = '***************'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('ebytyebyty#gmail.com', 'ebyty dokumenty');
// Add a recipient;
$mail->addAddress('drakxy998#gmail.com');
$mail->addAddress($email);
// Attachments
$mail->addAttachment('Objednávka'.$id_fakt.'.pdf', $name = 'Objednávka_'.$id_fakt.'.pdf', $encoding = 'base64', $type = 'application/pdf'); // Add attachments
$mail->addAttachment('Plnomocenstvo.pdf', $name = 'Plnomocenstvo.pdf', $encoding = 'base64', $type = 'application/pdf'); // Optional name
$mail->addAttachment('Súhlassospracúvanímosobnýchúdajov.pdf', $name = 'Súhlas_so_spracúvaním_osobných_údajov.pdf', $encoding = 'base64', $type = 'application/pdf');
$mail->addAttachment('Vyhlásenieomajetku.pdf', $name = 'Vyhlásenie_o_majetku.pdf', $encoding = 'base64', $type = 'application/pdf');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'ebyty dokumenty';
$mail->Body = 'text';
$mail->AltBody = 'ebyty dokumenty';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}`enter code here`

Weird $_POST behavior in PHPMailer

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;
}
?>

issue in sending mails in bulk in php

I am design a form for sending mail in bulk via phpMailer, for example i want to send a mail to 50 persons.but the issue is after sending mail 10 to 15 persons my form gives an file not found exception.
my ajax call is given below
.on('success.form.bv', function(e) {
e.preventDefault();
$('#send_email_next').modal({
backdrop: 'static'
});
$.ajax({
type: "POST",
url: "email_next.php",
data: $("#emailform").serialize(),
success: function(html){ $("#modal_body").html(html);}
});
});
Phpmailer function called in email_next.php is given below
require_once("class.phpmailer.php");
require_once("class.smtp.php");
$mail = new PHPMailer();
$body=" ";
set_time_limit(0);
$mail->IsSMTP();
$mail->Timeout = 10000;
$mail->SMTPKeepAlive = true;
$mail->SMTPDebug = false;
$mail->do_debug = 0;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = 'tls'; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port
$mail->Username = $account_user_name; // GMAIL username
$mail->Password = $password; // GMAIL password
$mail->From = $account_user_name;
$mail->FromName = 'Rayat Bahra Group';
$mail->Subject = $_POST['subject'];
$mail->AltBody = '';
$mail->WordWrap = 50;
$mail->MsgHTML($body);
$mail->MsgHTML($content);
$mail->IsHTML(true); // send as HTML
$SN = 0;
$error_mail=0;
$total_mails_to_send = count($email_array);
foreach($email_array as $recipient_address)
{
$mail2 = clone $mail;
$mail2->MsgHTML($content);
$mail2->AddAddress(trim($recipient_address));
$status = $mail2->Send();
if($status)
{
$SN++;
}
else{
$error_mail = 1;
}
echo $SN." out of ".$total_mails_to_send. " sent <br>";
}
if($error_mail == 1)
{
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
}
else{
echo "Message has been sent";
}
$mail->SmtpClose();

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?

how to send mail in php with image as body of the mail using PHP Mailer

$message.="<img src='cf_logo.png'/>";
the above code does not show the image in php
I need to show the image as body of the message.Not an attachment.
You need the full path:
<img src='add your domain here'/cf_logo.png>
Try below code:
$mail = new PHPMailer();
$mail->isSMTP(); // send via SMTP
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
//$mail->SMTPDebug = 2;
$mail->Host = $host; //SMTP server
$mail->Port = $port; //set the SMTP port; 587 for TLS
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
if (strlen($username)) {
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
} else {
$mail->SMTPAuth = false;
}
$mail->From = $from; // FROM EMAIL
$mail->FromName = $fromName; // FROM NAME
$mail->addAddress($to);
$mail->addReplyTo($from);
$mail->IsHTML($html);
$mail->Subject = $subject; // YOUR SUBJECT
$mail->Body = $message; // YOUR BODY
$mail->addAttachment($attachment); // YOUR ATTACHMENT FILE PATH
if ($mail->send()) {
echo "Message Sent";exit;
} else {
echo "Message Not Sent<br>";
echo "Mailer Error: " . $mail->ErrorInfo;exit;
}
Note: You need to include php mailer class.
Try this, it might work., Use http:// in the front of your image url like this
http://yoursite/folder/image.jpg

Categories