Is strip_tags necessary for phpmailer? - phpmailer

I'm using phpmailer with the following settings:
$mail->ContentType = 'text/plain';
$mail->IsHTML(false);
...
$mail->Body = $_POST['comments'];
$mail->Body = strip_tags($mail->Body);
I noticed strip_tags() cuts off the text if it hits a single greater than / less than sign (i.e if the user put in one of those characters legitimately).
Given that I have content type = 'text/plain' and ishtml = false, is it even necessary to have strip_tags() in there?

No, it is not neccesary. If you set $mail->isHTML(false) and you write HTML in the email, it is sent like text plain so it doesnt interpret it like HTML.
For example I've just done this:
$mail->ContentType = 'text/plain';
$mail->isHTML(false);
$mail->Subject = 'Your password';
$mail->Body = '<p>Your password is 123</p> Go to google ';
And the mail looks like this:
<p>Your password is 123</p> Go to google

Related

Missing part of content when automatic (crone) sending email by nodemailer

I have a strange problem. I made a small application in node.js, using nodemailer to send emails each day.
And it's working perfectly when I run it from the terminal (for testing).
But when I add a job to crontab, then emails are sent but there is missing some of the content inside.
This is my transporter conf:
// send mail with defined transport object
let info = await transporter.sendMail({
priority: 'high',
from: '"Example" <example#gmail.com>', // sender address
to: 'recip#gmail.com', // list of receivers
subject: 'Example title: '+currentDate, // Subject line
text: '', // plain text body
html: header + missing + carrierStatArr + ending,// html body
attachments: attachments
});
And code for variables to html field:
let carrierStatArr = [], attachments = [];
let header = `<h1>some text ${currentDate}</h1><div><i>some text</br>some text</i></div>`;
let missing = `<h3 style="color:red;">some text: <b>${missingArr}</b></h3>`;
for (let i in checkResultArr) {
let imgName = checkResultArr[i].file;
let correctedImgName = imgName.substring(0,16);
carrierStatArr.push(`<p>Some text <b>${checkResultArr[i].name}</b>,</br>
<span>Some text: <b>${checkResultArr[i].status}</b></span></br>
<span><img src="cid:${correctedImgName}" width="1000px"/></span>
</p>`);
}
//console.log(carrierStatArr);
attachments = checkResultArr.map((file)=>{
let pat = '/var/www/html/public_html/MM1_service/images/';
let fi = file.file;
let fit = fi.substring(0,16);
return {path: pat+file.file, cid: fit};
});
//console.log(attachments[0].path);
let ending = `<hr size="1" width="100%" color="gray"><p><i>some text</i></p>`;
Of course, there are all data in arrays. And as I wrote, when I run this code manually using terminal /node sendmail.js/ it works perfectly, email contains all the information's, text, and images.
But when the script is run automatically by the cron job, the email has only header, missing, and ending variables (and the content from arrays is there) but the rest: carrierStatArr, attachments are missing.
Why is that? Manually work, run by cron not exacly.
Note: I managed to solve my problem by using the 'node-cron' module instead of the system cron. The app is working correctly.
But still I'm curious, from an academic point, why that problem occurred.

How to Specify File Type and Size Limits With PHPMailer Mailing Multiple Attachments

Can someone please let me know using the PHPMailer how I can specifiy the limit of size and type of attachment?
For example if I want to enable Only PDF file to be attached and with limited size how I can update this part of the code?
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
Here is the entire code
<?php
require('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "YOUR USER_NAME";
$mail->Password = "YOUR PASSWORD";
$mail->Host = "YOUR HOST";
$mail->Mailer = "smtp";
$mail->SetFrom($_POST["userEmail"], $_POST["userName"]);
$mail->AddReplyTo($_POST["userEmail"], $_POST["userName"]);
$mail->AddAddress("RECIPIENT_EMAIL");
$mail->Subject = $_POST["subject"];
$mail->WordWrap = 80;
$mail->MsgHTML($_POST["content"]);
foreach ($_FILES["attachment"]["name"] as $k => $v) {
$mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}
$mail->IsHTML(true);
if(!$mail->Send()) {
echo "<p class='error'>Problem in Sending Mail.</p>";
} else {
echo "<p class='success'>Mail Sent Successfully.</p>";
}
?>
This isn't PHPMailer's responsibility – it's up to you to control the size and type of files before it gets to PHPMailer.
First of all, you're using a very old and unsupported version of PHPMailer, so upgrade to the latest version.
Secondly, your handling of uploads is unsafe. Follow the PHPMailer file upload example for how to do it safely.
In your form, set a hidden field named MAX_FILE_SIZE before your file input, set to whatever maximum size you want to impose:
<input type="hidden" name="MAX_FILE_SIZE" value="123456">
This can't actually control the size of submissions, but by convention, browsers will use it to reject oversize files before they are submitted, saving the user considerable hassle.
After validating the $_FILES element you're looking at (with move_uploaded_file, as in the example), take a look at the size of the submitted file by looking at the size element:
if ($_FILES['attachment']['size'] <= 123456) {
//We know file is under our size limit
To check the file type, extract the extension from the provided filename:
if (pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION) === 'pdf')) {
//We know file has a `.pdf` extension
For good measure, you could also check that the provided file type is what we want too:
if ($_FILES['userfile']['type'] === 'application/pdf')) {
//We know file has a PDF MIME type
After checking all of those things, you're now safe to pass the validated file to PHPMailer:
$mail->addAttachment($uploadedFilePath);

PHPMailer is causing long cc strings to separate

I use PHPMailer to send HTML emails. The code looks as follows:
$mail = new PHPMailer;
$mail->SMTPDebug = 3; // 3 = Enable verbose debug output
$mail->setFrom($mgr_email);
$mail->addReplyTo($mgr_email);
$mail->Encoding = 'base64';
$mail->isHTML(true);
// $legacy is an array we loop through of emails
$first = true;
foreach ($legacy as $x => $theiremail) {
if ($first == true) {
$mail->addAddress(trim($theiremail));
$first = false;
} else {
$mail->AddCC(trim($theiremail));
}
}
...
// later, we add an image every time (the company logo)
$mail->addEmbeddedImage($paths[$i]['path'], $paths[$i]['cid'], "image$i.jpg");
However, when I have many recipients, the email address string starts to break with a space in them, and always around the same spot. Example:
george#george.com, anyone#anyone.com, example#example.com, steven#we bsite.com
Steven here does not get the email. I've experienced something like this in HTML once where our longer emails just needed a space somewhere because our "headers" were a long, single word, but I can't figure out how to accomplish this with PHPMailer. In that case, all I had to do was add a space somewhere in the code. Any insight is appreciated.

Email template netsuite

I have really big problem, i mean im working in a company where we are using NetSuite as our business platform and now they updated our account with new APIs.
Developer before me wrote this code
for(var k = 0; k < ResultsPPCI.length; k++){
EmployeePPCI = ResultsPPCI[k].getValue('internalid'); //get the value
// log('Internal ID', EmployeePPCI);
// Merge, send, and associate an email with Purchase Order record (id=1000)
var mergeValuesPPCI = {};
mergeValuesPPCI.NLEMPFIRST = nlapiLookupField('employee', EmployeePPCI, 'firstname');
mergeValuesPPCI.NLEMPLAST = nlapiLookupField('employee', EmployeePPCI, 'lastname');
mergeValuesPPCI.NLSUPPLIER = nlapiLookupField('customer', cust, 'companyname');
mergeValuesPPCI.NLPRODUCTCODE = productcodehtml;
var emailBodyPPCI = nlapiMergeRecord(65, 'purchaseorder', poID, null, null, mergeValuesPPCI);
var recordsPPCI = {};
recordsPPCI['transaction'] = poID;
nlapiSendEmail(EmployeePPCI, EmployeePPCI, emailBodyPPCI.getName(), emailBodyPPCI.getValue(), null, null, recordsPPCI);
// log('EmployeePPCI',EmployeePPCI);
nlapiLogExecution('AUDIT', 'Potentional Problem', 'Email Sent');
}
I have problem now because nlapiMergeRecord is deprecated and it wont work. But i really cant find any working example online for hours... The most important part here is actually body of this email that has to be sent. In this case it is productcodehtml or mergeValuesPPCI.NLPRODUCTCODE.
This is how my template looks like :
<p>The QA Release has been submitted by <nlsupplier> for ${transaction.tranId}.</nlsupplier></p>
<p>The following item(s) have a short shelf life:</p>
<nlproductcode></nlproductcode>
Please can you help me with converting this code to new method? How can i connect nlproductcode from template with mergeValuesPPCI.NLPRODUCTCOD from my code?
Thanks in advance!
You can use kotnMergeTemplate as a drop in replacement for nlapiMergeRecord
e.g.:
kotnMergeTemplate(65, 'purchaseorder', poID, null, null, mergeValuesPPCI);
the nlobjEmailMerger does not take custom values so you'd have to post process the results. Again you can look at the example in my script where you'd get the merged string and then run:
var oldCustFieldPatt = /<(nl[^ >]+)>(\s*<\/\1>)?/ig;
content = content.replace(oldCustFieldPatt, function(a,m){
return mergeValuesPPCI[m.toUpperCase()] || mergeValuesPPCI[m.toLowerCase()] || '';
});
You can use the new nlapiCreateEmailMerger(templateId)
First you need to create your email template in netsuite and get the internal id.
Then:
Use nlapiCreateEmailMerger(templateId) to create an nlobjEmailMerger object.
var emailMerger = nlapiCreateEmailMerger(templateId);
Use the nlobjEmailMerger.merge() method to perform the mail merge.
var mergeResult = emailMerger.merge();
Use the nlobjMergeResult methods to obtain the e-mail distribution’s subject and body in string format.
var emailBody = mergeResult.getBody();
Send your email
nlapiSendEmail(senderInternalId, 'receiver#email.com','subject',emailBody, null, null, null);
Good luck!

phpmailer addBCC not storing addresses

I am using PHPMailer and use AddBCC to send to most of my addresses (only use 1 required in AddAddress). It seems to work okay (no errors), but I have found that it isn't saving (or sending to) all of the addresses that I process with $mail->AddBCC. It skips some of them, yet keeps others. So, when I do a print_r($mail->getBccAddresses()), I can see that it only has some of the email addresses. I am processing my lists of addresses in small groups, so I can control things better, so I wouldn't think there'd be any problems like this. I am including the applicable code from my program:
<?php session_start();
require '../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$emailist_cnt = 3;
for ($i=1; $i<= $emailist_cnt; $i++) {
//loop to gather email addresses into array $emailistAry[][]
}
// First, set up email message and required parameters.
$toname = "Grp-members";// Unused mailbox name
$fromname = "Webmaster";
$replyname ="Grpwebmaster";
$fromaddr = $fromname."#mydomain.org";
$toaddr = $toname."#mydomain.org";
$rplyaddr = $replyname."#gmail".".com";
$subject = "-- Website Update--";
$note1 = "New content has been added to the website";
$note2 = "Go check it out, if you want to stay up-to-date:";
$message = "Greetings HLCA Member! ".$note1." ".$note2;
// Set mail environment variables
$mail->isSMTP();
$mail->Host = 'smtp.hiddenlakeonline.org';
$mail->SMTPAuth = true;
$mail->Username = $fromname."#".$domain.".org";
$mail->Password = $webpass;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Set mail details that remain constant for every recipient
$mail->SetFrom($fromaddr);
$mail->AddAddress($toaddr);
$mail->AddReplyTo($rplyaddr);
$mail->Subject = $subject;
$mail->Body = $message;
$max_emails = 25; // max num emails per list
for ($i=1; $i <= $emailist_cnt; $i+=1) {
for ($j=1; $j <= $max_emails; $j+=1) {
// Addresses in current list will be added to BCC param.
if ($emailistAry[$i][$j] != '') {
$mail->AddBCC($emailistAry[$i][$j]); // add email to BCC }
} // for j loop
echo "would send to email list here. ";
print_r($mail->getBccAddresses());
// Clear cumulative recipient list for next loop
$mail->clearBCCs();
} // for i loop
?>
As you can see, I'm just doing a loop to add BCC entries. But, when I print out the getBCCaddresses array, there is always at least one email missing from each list. Is there a bug in PHP Mailer? Or am I doing something wrong?
I have seen a similar post (without any code) on another site (sourceforge.net?), but the question never got answered. Otherwise, there hasn't been anything similar that could help. Hopefully someone on here knows something about this.
Here are some results I get using echo outputs:
i,j,adding this email: 1,1,ImxEarth#gmail.com
i,j,adding this email: 1,2,heffxdog#me.com
i,j,adding this email: 1,3,imxearth#gmail.com
i,j,adding this email: 1,4,Aaronx72#yahoo.com
print: Array ( [0] => Array ( [0] => ImForEarth#gmail.com [1] => ) [1] => Array ( [0] => heffdog#me.com [1] => ) [2] => Array ( [0] => AaronTW72#yahoo.com [1] => ) )
Is it possible that phpMailer prevents duplicate addresses in BCC array?
I think I found my answer! It appears that AddBCC will only add unique email addresses to its array. So if an email address already exists in the BCCaddresses array, then the Mail->AddBCC('email') statement will not add it again. This becomes apparent when testing, because we often need to use duplicates to create a good size batch of emails. Well, you can process the duplicates, but they won't be added to the BCC parameter and won't be mailed more than once. Thx to all that responded!

Resources