I am using phpMailer, and i have a database table "list" with columns id|name|email|status.
What i am doing currently is using the phpMailer example
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$id = $_GET['id'];
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "smtp1.xample.com;smtp2.xample.com";
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "mail.example.com"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "no-reply#example.com"; // SMTP account username
$mail->Password = "password"; // SMTP account password
$mail->SetFrom('no-reply#example.com', 'Honda example');
$mail->AddReplyTo('no-reply#example.com', 'Honda example');
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
#MYSQL_CONNECT("localhost","root","password");
#mysql_select_db("osher");
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = #MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br />';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
Now the code above is db-email.php Where in if my table, email has over 100 entries with status as pending, i want to be able to using php. select each rows id and call db-email.php?id=xx (where x is the id) hence the email gets sent.
This works fine, if its done manually.
i needed you guys to help me, how best I can automate this process, that is to be able to push this 100 emails (without having to refresh the page)
assuming, I am on email.php where I can probably hit (a button) and it would simply start processing, each of the row in the email table, (instead of echo'n the result) I will be updating the database with status to = 'sent'
I am not sure if I have been very clear on what I want to ask, Please do help friends.
I believe someone with expertise in jQuery/AJAX or something could help me achieve this task :)
I'm not sure what your trying to do but, you can't do anything with databases or servers via javascript or jquery because there executed in the browser and not on the server.
You could use ajax to call certain .php files on the server with some parameters to do your job !
Related
I'm using the example mailing list and trying to tailor it to work with my DB. The problem I'm having is it's only sending to one email from the list of users in the Table (the example table only has 5 users). The email is being sent to the last user listed in the table
//Passing `true` enables PHPMailer exceptions
//$mail = new PHPMailer(true);
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = '####';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; //SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->Username = '###';
$mail->Password = '###';
$mail->setFrom('###', 'List manager');
$mail->addReplyTo('###', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$connection = mysqli_connect($server, $loginsql, $passsql, "database_name")
or die("Could not connect to database");
$result = mysqli_query($connection, 'SELECT user_login, user_email, db_prefix FROM userstest');
foreach ($result as $row) {
try {
$mail->addAddress($row['user_email'], $row['user_login']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['user_email']) . '<br>';
continue;
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['user_email']) . ' (' .
htmlspecialchars($row['user_email']) . ')<br>';
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['user_email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}
All - thanks for the help. I actually figured it out. The email address for setFrom was not the same as the account that was sending it out so it wouldn't work sending out to external domains.
I am trying to send two different emails to two different recipients using PHPmailer but only the second email is arriving.
My code:
/**
* This code shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require 'PHPMailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//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 - use full email address for gmail
$mail->Username = "olaozias#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "password";
//Set who the message is to be sent from
$mail->setFrom('olaozias#gmail.com', 'Department of Information Science');
//Set an alternative reply-to address
$mail->addReplyTo('olaozias#gmail.com', 'Department of Information Science');
//Set who the message is to be sent to
$mail->addAddress($email , 'Parent');
//Set the subject line
$mail->Subject = 'Student Attendance System';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->Body = 'Dear Parent \r\n This email is sent from the university of gondar , Department of information science to inform you that your child '. $firstname.' has been registered for semester '.$semister. ' in order to see your child attendance status and to communicate easily with our department use our attendance system. First download and install the mobile application which is attached in this email to your phone and use these login credentials to login to the system \r\n Your child Id: '.$student_no. '\r\n Password: '.$parent_pass.'\r\n Thank you for using our attendance system \r\n University of Gondar \r\n Department of Information Science ';
//Attach an image file
//$mail->addAttachment('AllCallRecorder.apk');
$mail->send();
$mail->ClearAddresses();
$mail->AddAddress($stud_email,'Student');
$mail->Subject = 'Student Attendance System';
$mail->Body = "email 2";
//send the message, check for errors
if (!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
echo '
<script type = "text/javascript">
alert("Mailer Error: " . $mail->ErrorInfo);
window.location = "student.php";
</script>
';
} else {
echo '
<script type = "text/javascript">
alert("student Added successfully and an Email the sent to email address provided");
window.location = "student.php";
</script>
';
//echo "Message sent!";
}
the second email is delivered successfully but the first one is not.
There are a couple of different possibilities. The fact that the second one is sending properly is a good indication that your code is working in general. Focusing on the first one, I'd suggest three things:
Add error checking to the first send() call. You have if (!$mail->Send()) {... on the second one, but you aren't checking the first one. You can use $mail->ErrorInfo as you have in a comment in the second part. (By the way, the $mail->ErrorInfo you have in the script tag will not work. Variables in single quoted strings like that will not be parsed, so you'll just get the literal string "$mail->ErrorInfo" there if there is an error.)
Add error checking to the first addAddress() call. PHPMailer will give you an error that you can check if the email address is invalid for some reason. As far as the code you've shown here, $email appears to be undefined, but so does $stud_email and you've said that one is working properly, so I assume those are both defined somewhere before the code that you've shown here, but a possible cause for this is that $email is undefined or doesn't have the value you expect it to.
The email is being sent, but not received. It's pretty easy for a message to be mis-identified as spam at multiple points between the sender and the receiver. This is more difficult to diagnose, but if you add the error checking to the first send() call and don't get any errors, you'll at least be able to rule that out as a point of failure.
you can do an array with de emails and subject.
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
I have a php page containing PHPMailer. Apperently it was working in both the test server and the production server. It was in a separate php file, but since I need to do send different kinds of email with different alert messages on screen, I placed my code on the same php file as my form.
What I did is:
if(isset($_POST))
{
require_once('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer(true);
if(isset($_POST['feedback_mail']))
{
$mail->Host = "my mail host"; // SMTP server
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Username = "the account that I will be using"; // SMTP account username
$mail->Password = "my password";
$mail->AddReplyTo($_POST['Email'], $_POST['Name']);
$mail->AddAddress('address to where I will send it', 'Name');
$mail->SetFrom($_POST['Email'], $_POST['Name']);
$mail->Subject = 'Subject'.$_POST['Subject'];
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($_POST['Body']);
$mail->Send();
$marker = 1;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$marker = 0;
} else {
$marker = 1;
}
}
}
When I try to send an email message, it says that the message is sent, but I have been waiting for almost an hour but there is still no message recieved on my email. I know that my test server allows sending of email because I also have another application that can send mails. And I am using the same account for sending these mails. How do I know if PHPMailer is really working or not?
EDIT: I found out it might probably be my local network connection that's stopping the mail. I just tried running the from on a VPN connection and somehow it recieved an email.
Either my network connection is having problems or the server is deliberately blocking IP's from my country.
Edit: I forgot I'd created the SendMail(); function myself, which is why the explanation doesn't mention at first what it does.
I'm having some trouble with PHPMailer (https://github.com/PHPMailer/PHPMailer) when attempting to send two emails, one directly after the other.
The script is almost completely 'out of the box', with only a few modifications such as a foreach loop to allow for multiple addresses, and everything still works perfectly.
However, if I attempt to call more than one instance of SendMail(); I get the error message:
Fatal error: Cannot override final method Exception::__clone() in .... online 0
Previously I was using the in-built mail(); function, which allowed me to use it as many times as I liked in quick succession , but it doesn't appear to be that simple with PHPmailer:
$to = me#me.com;
$to2 = me2#me2.com';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
The above would result in two identical emails being sent to different people, however I can't easily replicate this functionality with PHPmailer.
Is there a way of stacking these requests so that I can send successive emails without it failing? Forcing the script to wait until the first email has been sent would also be acceptable, although not preferential.
As I mentioned I know it works when only one instance is called, but I don't seem to be able to re-use the function.
I haven't included the source code, although it is all available on the link provided above.
Thanks in advance
Edit as requested
// First Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;
sendMail();
// Second Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;
sendMail();
The above is how I want this to work, as it would work with mail();. The first email will work fine, the second will not.
SendMail() code
This is from the PHPmailer website, and is what is defined as SendMail();. The only difference from the example is the loop for AddAddress, and the inclusion of $to as a global variable.
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "from#example.com";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add); // name is optional
}
$mail->AddReplyTo("info#example.com", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
You haven't posted this code that lets me make this a complete conclusion, but from the Exception and the way you've defined an overriding class inside a function, you probably have class.phpmailer.php loading every time like this:
require('class.phpmailer.php');
or
include('class.phpmailer.php');
You should change that line to
require_once('class.phpmailer.php');
The reason you need to change it to require_once is so that PHP will not load the class file the second time when you try to create the new/second PHPMailer class. Otherwise, the line class PHPMailer throws the __clone() exception.
Added an example below:
<?php
/**
* This example shows how to send a message to a whole list of recipients efficiently.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../vendor/autoload.php';
//Passing `true` enables PHPMailer exceptions
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html');
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = 'yourname#example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('list#example.com', 'List manager');
$mail->addReplyTo('list#example.com', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('localhost', 'username', 'password');
mysqli_select_db($mysql, 'mydb');
$result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = FALSE');
foreach ($result as $row) {
try {
$mail->addAddress($row['email'], $row['full_name']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
if (!empty($row['photo'])) {
//Assumes the image data is stored in the DB
$mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['full_name']) . ' (' . htmlspecialchars($row['email']) . ')<br>';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE mailinglist SET sent = TRUE WHERE email = '" .
mysqli_real_escape_string($mysql, $row['email']) . "'"
);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}
In addition to #Amr most excellent code.
In order to use this in a cron fasion, two adds are useful.
$mail-> SMTPDebug = true;
$mail-> Debugoutput = function( $str, $level ) {_log($str);};
The function _log is up to you. Writing to a file, to a database or wherever. I personally have reduced this to
$mail-> Debugoutput = function( $str, $level ) {if( $level===3 ) {_log( $str ); } };
to only write the more juicier messages
the solution is to reset recipients data like this:
$Mailer->clearAddresses()
use your own variable as an instance of PHPMailer (instead of $Mailer)
$Mailer->clearAddresses()
This is the solution to avoid multiple msj to be send to the same recipient.
I need help in sending multiple emails from database using PHP. I have a code that work, but it can only allow one email in it. Is there some way to modify it to help me send multiple ones?
<?
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
//Gmail configuration
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "******#gmail.com"; // GMAIL username
$mail->Password = "785123nick"; // GMAIL password
$prize = "lol";
//End Gmail
$mail->From = "from#email.com";
$mail->FromName = "Jetstar";
$mail->Subject = "Order Redemption";
$mail->MsgHTML("You have bought " . $prize . " Print this and collect it at our office.");
//$mail->AddReplyTo("reply#email.com","reply name"); //They answer here, optional
$mail->AddAddress("your-email","name to");
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) { //To see if we return a message or a value bolean
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
echo "Message sent!";
?>
Assuming that you would like to send same email to multiple recipients and that your email addresses are stored in a database, you may do something like this:
read email addresses from your database table
loop through the email addresses and pass each email address to $mail->AddAddress();
This way you can add multiple email addresses to your mail object and then send to all.
Hope it helps!
Using phpmailer, you may add multiple recipients simply calling addAddress multiple times...
Obviously, as suggested before, you may want to call this script by mean of a cronjob, thus respecting limits imposed by the mail server.