Phpmailer - Getting multiple entries of custom headers while looping - php

This is my mailing script, i m using for loop to send multiple emails.
if(isset($_POST['submit'])){
require ("vendor/autoload.php");
$fr_email = $_POST['fr_email'];
$from = $_POST['from'];
$reply_to = $_POST['reply_to'];
$sub = $_POST['sub'];
$tm = $_POST['email'];
$str = "<117418239>
<128422057>";
$listid= explode("\n",$str);
$mail = new PHPMailer\PHPMailer\PHPMailer;
for ($x = 2; $x > 0 ; $x--){
$mail->isSMTP();
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
));
$mail->SMTPDebug = 0;
$mail->Host = 'hostname';
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->Username = 'uname';
$mail->Password = 'pwd';
$mail->SMTPSecure = 'tls';
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->isHTML(true);
$mail->setFrom($fr_email,$from);
$mail->AddReplyTo($reply_to,$from);
$mail->Sender=$fr_email;
$mail->Subject=$sub;
$mail->XMailer = ' ';
$mail->addCustomHeader('List-ID', $listid[$x-1]);
$body = $_POST['body'];
$mail->Body=$body;
//$mail->AltBody=$altbody;
$mail->addAddress($tm);
if ($mail->send()) {
echo "\nMessage sent\n";
}
else {
echo 'Mailer error: ' . $mail->ErrorInfo;
}
$mail->clearAddresses();
$mail->SmtpClose();
} // for loop close
}
I'm using "addcustomheader" function to add list id header field. Bcoz i m running a loop i m getting multiple entries of list id field in my email header. [even though i m closing my smtp connection after each iteration]
for 1st email
List-ID: <117418239>
for 2nd email
List-ID: <117418239>
List-ID: <128422057>
Is there a way to clear the custom headers after each iteration of the loop, like clearing the email address

Yes. Note the name of the method addCustomHeader – it adds a header, and does not replace existing ones. To fix this, call clearCustomHeaders() after sending within your loop. See the docs on this method.

Related

How to send a longer mail with php

I have been trying to send emails with PHP, but whenever the message gets too long the mail isn't sent.
This is what I have so far:
$name= $_POST["name"];
$email= $_POST["email"];
$comment= $_POST["text"];
$msg= "Naam: " . $name . "\r\nEmail: " . $email . "\r\nBericht: " . $comment;
mail("test.test#live.nl", "Website", $msg);
I don't recommend that you do it this way, since emails can get spam.
I recommend you use phpmailer.
I leave you an example:
try {
$mail = new PHPMailer(true);
//Server settings
$mail->isSMTP();
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#example.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//Recipients
$mail->setFrom('example#example.com', 'name');
if(is_array($this->Emails)){
foreach($this->Emails as $email){
$mail->addAddress($email); // Add a recipient
}
}
else{
$mail->addAddress($this->Emails); // Add a recipient
}
if(isset($this->Attachments)){
if(is_array($this->Attachments)){
foreach($this->Attachments as $Attachment){
$mail->addAttachment($Attachment); // Add attachments
}
}
else{
$mail->addAttachment($this->Attachments); // Add attachments
}
}
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $this->Subject;
$mail->Body = $this->Body;
$mail->send();
return true;
I'm recommending this because your method in sending an email in PHP is very out dated now, it will save you many headaches.
Use Composer
Install Swiftmailer like this composer require swiftmailer/swiftmailer
Much easier to manage emails

multiple attachments going with single mail from phpmailer

I am sending payslip mails with payslips as attachment with phpmailer class. the problem is the first mail is going with one attachment but the sedonf mail is going with the first and the second attachments together.
For example:
mail for employee name : A is going with A.pdf
mail for employee name : B is going with A.pdf and B.pdf
need some help. my project completion date is tomorrow and I am stuck in this last problem.
this is my code:
<?php
require_once 'mailerClass/PHPMailerAutoload.php';
require_once '../connect.php';
$mail = new PHPMailer;
//$mail->isSMTP();
$sql = "SELECT * FROM mail ORDER BY Id";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($query, MYSQL_ASSOC)){
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username ='riteshrc13#gmail.com';
$mail->Password = "password";
$mail->setFrom('64mediakraft#gmail.com', 'Mediakraft');
$mail->addAddress($row['Email'], $row['Name']);
$mail->Subject = "Payslip of " . $row['Name'];
$mail->Body = "payslip email";
$mail->AltBody = 'Payslip Email for the month. Please find the payslip attached.';
$mail->isHTML(true);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$pdf = "C:/Reports/" . $row['Name']. ".pdf";
$mail->addAttachment($pdf);
if ($mail->send()) {
echo "<script>alert('Mail Sent success');</script>";
// header("Location:index.php");
}
else {
echo "<script>alert('Mailer Error: ' $mail->ErrorInfo);</script>";
// header("Location: index.php");
}
$pdf = "";
} //endwhile
?>
Creating a new instance inside the loop will work, but it's very inefficient and means you can't use keepalive, which makes a huge difference to throughput.
Base your code on the mailing list example provided with PHPMailer which shows how to send most efficiently, and read the docs on sending to lists. To paraphrase that example, it should go roughly like this:
$mail = new PHPMailer;
//Set properties that are common to all messages...
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->Host = 'mail.example.com';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Subject = 'Hello';
$mail->From = 'user#example.com';
//etc
//Loop over whatever resource gives you your recipients
foreach ($result as $target) {
//Set properties that are specific to this message
$this->addAddress($target['email']);
$this->addAttachment($target['file']);
//Send the message
$this->send();
//All done, so clear recipients and attachments for next time around
$mail->clearAddresses();
$mail->clearAttachments();
}
Don't forget to add some error checking in there, and I can also see that you're using an old version of PHPMailer - so get the latest, and base your code on the mailing list example.
$mail = new PHPMailer; // this should be inside of while, I think...
Thanks to #jonStirling and #toor for the help.
complete working code for other help seekers:
<?php
require_once 'mailerClass/PHPMailerAutoload.php';
require_once '../connect.php';
//$mail->isSMTP();
$counter = 1;
$sql = "SELECT * FROM mail ORDER BY Id";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($query, MYSQL_ASSOC)){
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = false;
$mail->Username ='riteshrc13#gmail.com';
$mail->Password = "password";
$mail->setFrom('64mediakraft#gmail.com', 'Mediakraft');
$mail->addAddress($row['Email'], $row['Name']);
$mail->Subject = "Payslip of " . $row['Name'];
$mail->Body = "payslip email";
$mail->AltBody = 'Payslip Email for the month. Please find the payslip attached.';
$mail->isHTML(true);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$pdf = "C:/Reports/" . $row['Name']. ".pdf";
$mail->addAttachment($pdf);
if ($mail->send()) {
echo "<script>alert('Mail Sent success');</script>";
// header("Location:index.php");
}
else {
echo "<script>alert('Mailer Error: ' $mail->ErrorInfo);</script>";
// header("Location: index.php");
}
$pdf = "";
$mail->clearAttachments();
} //endwhile
?>

Send Mass E-mail PHPMAILER through G-Suite

So i have the following code:
while(list($i, $data_subscriber) = each($subscriber)) {
$email_counter = $i + 1;
echo ($email_counter).') '.$data_subscriber->field_1.' '.$data_subscriber->field_2.' - '.$data_subscriber->email.''."\n";
flush();
$language = $data_subscriber->lang;
$body_mail = include($template_send_newsletter);
$first_name_idx = $data_subscriber->field_1;
$last_name_idx = $data_subscriber->field_2;
if (mail_send(strtolower($data_subscriber->email),
( IsSet($first_name_idx) && IsSet($last_name_idx) ? $first_name_idx.' '.$last_name_idx : $data_subscriber->email ),
$site_admin,
$site_name,
'Newsletter ['.date('d/m/Y', time()).']',
true,
$body_mail,
NULL,
false)) {
reset($data_subscriber->newsletter_item);
unset($log_detail);
$log_detail = "";
while(list($j, $list_of_news_to_send) = each($data_subscriber->newsletter_item)) {
$log_detail = ( IsSet($list_of_news_to_send->title) ? $list_of_news_to_send->title."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->subtitle) ? $list_of_news_to_send->subtitle."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->creation_date) ? $list_of_news_to_send->creation_date."\n" : '');
$log_detail = "\n";
} /* end while */
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'Y',
$log_detail);
}
else {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'N',
NULL);
} /* end if mail_send */
} /* end while */
And the following function
function mail_send($rcpt_to,
$to_name,
$mail_from,
$from_name,
$subject,
$isHTML = true,
$body,
$attachment = NULL,
$direct_delivery = false,
$reply_to = NULL){
$mail = new PHPmailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "mail#domain.com";
$mail->Password = "password";
$mail->Timeout = 3600;
$mail->addAddress(trim($rcpt_to), trim($to_name));
$mail->setFrom($mail_from,$from_name);
$mail->Subject = $subject;
$mail->Body = $body;
if ($isHTML) {
$mail->IsHTML(true);
$mail->AltBody = strip_tags($mail->Body);
}
if (IsSet($attachment)) {
$mail->AddAttachment($attachment['tmp_name'], $attachment['name']);
}
if (IsSet($reply_to)) {
$mail->AddReplyTo($reply_to);
}
if (!$mail->send()) {
return false;
} else {
return true;
}
}
I am using PHPMailer to send multiple e-mails using gmail SMTP server.
I have 4 files containing different but almost the same code to send newsletter.
One of my files is sending all the emails to ( ~60 recipients )
The other 3 files, each of them needs to send one email to ~600 recipients.
Problem occures here, half of the e-mails are sent the other are not.
If I run the script but this time for fewer recipients witch didn't recieved the e-mail first time, it's sending.
I'm using GMAIL with my own domain. So i'm not exceeding any limit.
What may cause this problem ? Any ideas ? Thank you.
UPDATE**
SERVER -> CLIENT: 454 4.7.0 Too many login attempts, please try again later. e11sm950198edd.68 - gsmtp
After some emails that are sent i recieve this error. Any ideas why ?
UPDATE***
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->Username = "domain#domain.com";
$mail->Password = "password";
$mail->setFrom($site_noreply, $site_name);
$subjectnewsletter = 'Newsletter ['.date('d/m/Y', time()).']';
$mail->Subject = $subjectnewsletter;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
reset($subscriber);
while(list($i, $data_subscriber) = each($subscriber)) {
$email_counter = $i + 1;
echo ($email_counter).') '.$data_subscriber->field_1.' '.$data_subscriber->field_2.' - '.$data_subscriber->email.''."\n";
flush();
$language = $data_subscriber->lang;
$first_name_idx = $data_subscriber->field_1;
$last_name_idx = $data_subscriber->field_2;
$fullname = $first_name_idx.' '.$last_name_idx;
$bodymail = include($template_send_newsletter);
$mail->msgHTML($bodymail);
$mail->addAddress($data_subscriber->email, $fullname);
reset($data_subscriber->newsletter_item);
unset($log_detail);
$log_detail = "";
while(list($j, $list_of_news_to_send) = each($data_subscriber->newsletter_item)) {
$log_detail = ( IsSet($list_of_news_to_send->title) ? $list_of_news_to_send->title."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->subtitle) ? $list_of_news_to_send->subtitle."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->creation_date) ? $list_of_news_to_send->creation_date."\n" : '');
$log_detail = "\n";
} /* end while */
if (!$mail->send()) {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'N',
NULL);
echo $mail->ErrorInfo;
break; //Abandon sending
} else {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'Y',
$log_detail);
echo "Message sent";
}
$mail->clearAddresses();
$mail->clearAttachments();
} /* end while */
I managed to change my code so it's not connect to the smtp server every e-mail.
But now after it sends 93 emails i get the follosing error:
SMTP server error: MAIL FROM command failed
You need to use an MTA that uses more than one connection and it already setup to respect limits of the servers you're connecting to. At this point you're attempting to exceed the limits of the server you're connecting to and companies like Google frown on too many connections or using their mail servers for broadcasts.
Look for a mail sending service if your numbers are modest, or consider purchasing and hosting an MTA if you send a considerable amount of email.
You can use SMTP relay configuration which allow you to send email from your server with any of your email domain address.

PHP sending emails to but not text

I am trying to send emails to phones that have Verizon numbers. Here is my code right now
<?php require('includes/config.php');
function Send( $ToEmail, $MessageHTML, $MessageTEXT) {
require_once ( 'classes/phpmailer/phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "box405.bluehost.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "ssl"; //Secure conection
$Mail->Port = 465; // set the SMTP port
$Mail->Username = 'techsupport#test.com'; // SMTP fake account username
$Mail->Password = 'password1'; // SMTP fake account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->FromName = 'Tech support';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$stmt = $db->prepare("select phone From members where phone not like 'no';");
$stmt->execute();
$result = $stmt->fetchAll();
$ToEmail = $result[0][0];
$ToName = 'techsupport';
$MessageHTML = "test";
$MessageTEXT = 'test';
$Send = Send( $ToEmail, $MessageHTML, $MessageTEXT);
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
this works when I try to send emails but when I use it to send texts it says sent but I do not receive anything. I know this is not because of the address because I use the same address when I text myself from gmail and it is not the sql query because I have tested it . I Think the problem is in the smtp or phpmailer for I have not used either of those a lot. Also the code runs though and prints out the SENT OK echo but nothing goes through and no errors.
[EDIT] To answer ironcito's question I am sending the email to
phonenumber#vtext.com
I know this works because I have used the same address through gmail.
I think this might be because you push the content to the mail (body) before you set the content (messagehtml/messagetext), which creates an empty email. Try changing these around, that might be the solution.

PHPMailer, SMTP connect() failed error with Gmail

I’m trying to make a contact form and I’m using PHPMailer. I tried that on localhost with xampp and it works perfect. But when i upload to my host i get the error SMTP connect() failed.
Here is my code:
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = "smtp.gmail.com";
$m->Username = "mymail#gmail.com";
$m->Password = "mypass";
$m->SMTPSecure = "ssl";
$m->Port = "465";
$m->isHTML();
$m->Subject = "Hello world";
$m->Body = "Some content";
$m->FromName = "Contact";
$m->addAddress('mymail#gmail.com', 'Test');
I've tried to change the port to 587 and the SMTPsecure to tls (and all the combinations). But doesn’t work. Any advice to solve this?
Thanks
This answer work form me: https://stackoverflow.com/a/47205296/2171764
I use:
$mail->Host = 'tls://smtp.gmail.com:587';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
You may need to specify the address from which the message is going to be sent, like this:
$mail->From = 'user#domain.com';
I would also give isHTML a parameter, either true or false:
$m->isHTML(true);
Another option is trying to drop the port specification all together. There are several other parameters that you may find useful. The following example is code I've tested, see if you can adapt it for your uses:
$mail = new PHPMailer;
$mail->isSMTP();/*Set mailer to use SMTP*/
$mail->Host = 'mail.domain.com';/*Specify main and backup SMTP servers*/
$mail->Port = 587;
$mail->SMTPAuth = true;/*Enable SMTP authentication*/
$mail->Username = $username;/*SMTP username*/
$mail->Password = $password;/*SMTP password*/
/*$mail->SMTPSecure = 'tls';*//*Enable encryption, 'ssl' also accepted*/
$mail->From = 'user#domain.com';
$mail->FromName = $name;
$mail->addAddress($to, 'Recipients Name');/*Add a recipient*/
$mail->addReplyTo($email, $name);
/*$mail->addCC('cc#example.com');*/
/*$mail->addBCC('bcc#example.com');*/
$mail->WordWrap = 70;/*DEFAULT = Set word wrap to 50 characters*/
$mail->addAttachment('../tmp/' . $varfile, $varfile);/*Add attachments*/
/*$mail->addAttachment('/tmp/image.jpg', 'new.jpg');*/
/*$mail->addAttachment('/tmp/image.jpg', 'new.jpg');*/
$mail->isHTML(false);/*Set email format to HTML (default = true)*/
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
header("Location: ../docs/confirmSubmit.html");
}
Hope this helps!

Categories