Send email to each checked row - php [duplicate] - php

This question already has answers here:
PHP send email foreach - send to
(2 answers)
Closed 8 years ago.
I would like to know how to make a loop to make it send email to each checked row from php table.
Here's the table row for checkboxes:
echo "<input name=\"approve[]\" type=\"checkbox\" value='".$row["id"]."' >";
Approve php:
$pfw_header .= "MIME-Version: 1.0\r\n";
$pfw_header .= "Content-type: text/html; charset=utf-8\r\n";
$fromName = "HP EG NPI - Registracija";
$fromEmail = "hp_eg_npi#eventregistration.rs";
$toEmail = "$email";
$subject = "Prijava prihvacena";
function sendEmail ($fromName, $fromEmail, $toEmail, $subject, $emailBody, $pfw_header) {
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
$mail->AddAddress("$toEmail");
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
}
function readTemplateFile($FileName) {
$fp = fopen($FileName,"r") or exit("Unable to open File ".$FileName);
$str = "";
while(!feof($fp)) {
$str .= fread($fp,1024);
}
return $str;
}
//Data to be sent (Ideally fetched from Database)
$name = "$first_name";
$lastname = "$last_name";
$UserEmail = "$email";
//Send email to user containing username and password
//Read Template File
$emailBody = readTemplateFile("../html-email/mail2.html");
//Replace all the variables in template file
$emailBody = str_replace("#username#",$fnames,$emailBody);
$emailBody = str_replace("#password#",$lnames,$emailBody);
//Send email
$emailStatus = sendEmail ($fromName, $fromEmail, $UserEmail, $subject, $emailBody, $headers);
}
}
}
I have tried searching around the internet, but couldn't manage to find a solution.
Thanks in advance!

You could just do:
$mail = new PHPMailer();
$mail->FromName = $fromName;
$mail->From = $fromEmail;
foreach($emails as $email) {
$mail->AddAddress("$email");
}
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->isHTML(true);
$mail->WordWrap = 150;
if(!$mail->Send()) {
return false;
} else {
return true;
}
You don't need the sendEmail function.

Related

Cannot redeclare Send_mail() error

I m trying to make a function which can check the database for active customer whose status is 1 if active, they should receive email.
For Email Functionality I had used PHP Mailer function.
Below is my script:
<?php
include '../mailer/class.phpmailer.php';
$sqlx = mysql_query("SELECT * from `cust");
$numRows = mysql_num_rows($sqlx);
$mail_body = '';
while($row = mysql_fetch_array($sqlx))
{
// fetch email
$uid = $row["uid"];
$email = $row["email"];
$count = "20";
if($count <= '70')
{
$f_name = "abc";
$f_email = "abc#xyz.com";
$mail_body = "Hii message";
$subject = "Hi you got notificaiton";
$headers = "From: abc <abc#xyz.com>";
$headers .= "Content-type: text/html\r\n";
function Send_mail($email, $subject, $headers, $mail_body, $f_email, $f_name)
{
$mail = new PHPMailer();
$Email = $email;
$fname = $f_name;
$femail = $f_email;
//==================smtp mail ===============================//
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Port= 25; // Sets the default SMTP server port.
$mail->SMTPSecure= 'tls'; // Options are "", "ssl" or "tls"
$mail->Host = 'localhost'; // SMTP server
$mail->Username = 'abc#xyz.com'; // Sets SMTP username.
$mail->Password = '1234556'; //Sets SMTP password.
//=========================================================//
$fname = $f_name;
$femail = $f_email; // email address of reciever
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = $subject; // subject of mail
$mail->Body = $mail_body; // body of mail
$mail->Send(); return true;
}
$mail_result=Send_Mail($email, $subject, $headers, $mail_body,$f_email, $f_name);
}
}
?>
But i getting error:
You must provide at least one recipient email address.
Fatal error: Cannot redeclare Send_mail() (previously declared in C:\xampp\htdocs\testing\update.php:161) in C:\xampp\htdocs\testing\update.php on line 161
check your cust table there must be entered email address on which you are trying to send email. And change your
$mail->Port= 587;
$mail->SMTPSecure= 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Username = 'abc#gmail.com';//Valid Gmail address
$mail->Password = '1234556';//Gmail password
if still getting error you can go to your gmail account setting and allow for secure app authentication.
take your function outside of loop.Change your code structure to this.
function Send_mail($email, $subject, $headers, $mail_body, $f_email, $f_name)
{
................//code
$mail->Send(); return true;
}
while($row = mysql_fetch_array($sqlx))//use mysqli or PDO
{
.......//code
if($count <= '70')
{
.......//code
$mail_result=Send_mail($email, $subject, $headers, $mail_body,$f_email, $f_name);
}
}
Put your function outside of the loop. Here is the code structure:
<?php
include '../mailer/class.phpmailer.php';
function Send_Mail($email, $subject, $headers, $mail_body, $f_email, $f_name)
{
$mail = new PHPMailer();
$Email = $email;
$fname = $f_name;
$femail = $f_email;
//==================smtp mail ===============================//
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Port= 25; // Sets the default SMTP server port.
$mail->SMTPSecure= 'tls'; // Options are "", "ssl" or "tls"
$mail->Host = 'localhost'; // SMTP server
$mail->Username = 'abc#xyz.com'; // Sets SMTP username.
$mail->Password = '1234556'; //Sets SMTP password.
//=========================================================//
$fname = $f_name;
$femail = $f_email; // email address of reciever
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = $subject;// subject of mail
$mail->Body = $mail_body; // body of mail
$mail->Send();
return true;
}
$sqlx = mysql_query("SELECT * from `cust");
$numRows = mysql_num_rows($sqlx);
$mail_body = '';
while($row = mysql_fetch_array($sqlx))
{
// fetch email
$uid = $row["uid"];
$email = $row["email"];
$count = "20";
if($count <= '70')
{
$f_name = "abc";
$f_email = "abc#xyz.com";
$mail_body = "Hii message";
$subject = "Hi you got notificaiton";
$headers = "From: abc <abc#xyz.com>";
$headers .= "Content-type: text/html\r\n";
$mail_result=Send_Mail($email, $subject, $headers, $mail_body,$f_email, $f_name);
}
}
?>

error:"couldn't instantiate mail function"

I am using Windows. When I try to send mail using php mailer. It returns "couldn't instantiate mail function". Is it some permission issue or is there anything wrong with code? Thanks!
<?php
require_once("class.phpmailer.php");//location is correct
require_once("class.smtp.php");//location is correct
$to_name = "Good Better";
$to = "sending#example.com";
$subject = "Mail Test at ".strftime("%T", time());
$message = "This is a test.";
$message = wordwrap($message,70);
$from_name = "My Name";
$from = "myacc#example.com";
$mail = new PHPMailer();
$mail->FromName = $from_name;
$mail->From = $from;
$mail->AddAddress($to, $to_name);
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
echo $result ? 'Sent' : $mail->ErrorInfo;
?>

cannot send email to multiple recepients using phpmailer

I'm trying to send an email to multiple recipients using phpmailer and getting the emails list from my table in the database, however, whenever I make a request only one recipient, the first one on the list gets the email. *I know this might be marked as duplicate but I couldn't find a similar example using mysql
<?php
if (isset($_POST['submit'])) {
if (empty($errors)) {
$thisType = mysql_prep($_POST["partner_type"]);
$content = $_POST["content"];
$header = $_POST["header"];
$query = "SELECT * FROM partners_list WHERE partner_type = '$thisType' ";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/class.smtp.php");
require_once("phpMailer/language/phpmailer.lang-uk.php");
$to_name = "Order";
$subject = $header;
$message = $content;
$message = wordwrap($message,70);
$from_name = "thisCompany";
$from = "noreply#thicCompany.com";
$mail = new PHPMailer();
$mail->AddAddress($row['email'], "Test Message"); // add each DB entry to list of recipients
$mail->FromName = $from_name;
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $message;
$result = $mail->Send();
// Success
$_SESSION["message"] = "e-mail successfully sent.";
redirect_to("successpage.php");
}
}
} else {
}
?>

Attachments working intermittently

I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>

Mail send with PHPMailer doesn't work

So I'm trying to use PHPMailer to handle the email form on my website.
I wrote the code here based on a tutorial I found.
<?php
error_reporting(E_ALL);
require_once("class.phpmailer.php");
include("class.smtp.php");
$email = new PHPMailer();
//
// Set server details for send
//
$email->IsSMTP();
$email->Host = "mail.loganyoung.za.net";
$email->Port = 25;
$email-SMTPAuth = true;
$email->Username = "<my email>";
$email->Password = "<my password>";
//
// Send mail from the contact form
//
$to = "<my email>";
$from = $_POST["from"];
$name = $_POST["name"];
$subject = "From web: ".$_POST["subject"];
$message = $_POST["message"];
$body = "<p>Hi Logan,</p>";
$body .= "<p>You have received a new query on your website.<br />Please see below:</p>";
$body .= "<p>";
$body .= str_replace("\r\n", "<br />", $message);
$body .= "</p>";
$email->SetFrom($from, $name);
$email->AddReplyTo($from, $name);
$email->AddAddress($to, "LoganYoung.za.net");
$email->Subject = $subject;
$email->Body = $body;
$email->IsHTML = true;
session_start();
if(!$email->Send()) {
$_SESSION["mailresult"] = "success";
echo "success";
} else {
echo "<p>Failed:</p><p>".$email->ErrorInfo."</p>";
$_SESSION["mailresult"] = "failed";
$_SESSION["mailerror"] = $email->ErrorInfo;
}
?>
I figure possible reasons for it not sending could be...
Incorrect SMTP details (possibly send without SMTP auth to resolve?)
Handler isn't getting POST data (the ajax that sends it seems to work fine though)
Some problem with this code that I'm not able to identify...
As a means of eliminating possibilities, can anyone spot anything wrong with the code here? If so, what's wrong, and how do I fix it?
Thanks in advance!
$email-SMTPAuth = true;
Isn't that supposed to be:
$email->SMTPAuth = true;

Categories