Send multiple emails from a database using PHP - php

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.

Related

Mailgun with PHP

I've been trying to implement a contact service using Mailgun coded in PHP. I receive the following error:
Could not connect to SMTP host
Below is my code:
<?php
require("../includes/config.php");
require("../mailgun-php/vendor/autoload.php");
require("../phpmailer/_lib/class.phpmailer.php");
use Mailgun\Mailgun;
if($_SERVER["REQUEST_METHOD"] === "GET")
{
render("contact-form.php", ["title" => "Contact us"]);
}
if($_SERVER["REQUEST_METHOD"] === "POST")
{
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mailgun.org'; // Specify mailgun SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'postmaster#sandboxb9cc446d8b7240efa59917c68fae6e50.mailgun.org'; // SMTP username from https://mailgun.com/cp/domains
$mail->Password = '*SMTP password from sandbox domain'; // SMTP password from https://mailgun.com/cp/domains
$mail->SMTPSecure = 'sll'; // Enable encryption, 'ssl'
$mail->Port= '465';
$mail->From = 'sandboxb9cc446d8b7240efa59917c68fae6e50.mailgun.org'; // The FROM field, the address sending the email
$mail->FromName = 'Enquiry bot'; // The NAME field which will be displayed on arrival by the email client
$mail->addAddress('****#gmail.com'); // Recipient's email address and optionally a name to identify him
$mail->isHTML(true); // Set email to be sent as HTML, if you are planning on sending plain text email just set it to false
// The following is self explanatory
$mail->Subject = 'Client enquiry';
$mail->Body = $_POST["message"];
if(!$mail->send())
{
echo "Message hasn't been sent.";
echo 'Mailer Error: ' . $mail->ErrorInfo . "\n";
}
else
{
redirect("confirmation.html");
}
}
?>
Note that this is the controller (I'm using MCV).
This is part of a website I've been implementing as a project for a CS class. Therefore I would avoid buying a private domain.
UPDATE: I've modified the original post with how this piece of code should be. May anyone else encounter this issue, this snippet is working without any issue.
I've contacted the Mailgun staff which provided me with excellent support. The problem lies with how I specify the port. It should be 465 for SSL and 587 for TLS.

customizing mail sending form in php using core php

Well i am in need of little help here.
I am doing a php custom mail sending form in which i need to make custom option for user to setup - port, host, smtp email, smtp pass, smtp username, also there is option to enable or disable smtp, Those all are working, but i have a situation here.
i also want to enable SSL Option for user, so if user select SSL is yes then it will send using SSL to prevent email going to SPAM. but i am unable to do this, can anyone help me with this.
here is code that i am using please check and assist anyone-
https://www.dropbox.com/s/m7ltrl8q0dxic4v/smtpmail-dummy.zip?dl=0
Here for this set the SMTPSecure property of PHPMailer class to 'ssl'. Then connect it using SmtpConnect() method.
So basically you can write a code like below. Not exactly, just for reference.
<?php
$mail = new PHPMailer; // call the class
$mail->IsSMTP();
$mail->Host = SMTP_HOST; //Hostname of the mail server
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->SMTPAuth = true; //Whether to use SMTP authentication
$mail->Username = SMTP_UNAME; //Username for SMTP authentication any valid email created in your domain
$mail->Password = SMTP_PWORD; //Password for SMTP authentication
$mail->AddReplyTo("developer#vrstamphead.com", "Developer Rakesh");
//reply-to address
$mail->SetFrom("developer#vrstamphead.com", "Developer Rakesh"); //From address of the mail
// put your while loop here like below,
$mail->Subject = "Your SMTP Mail"; //Subject od your mail
$mail->AddAddress($email, "Asif18"); //To address who will receive this email
$mail->MsgHTML("<b>Hi, your first SMTP mail has been received. Great Job!.. <br/><br/>by <a href='http://www.asif18.com/7/php/send-mails-using-smtp-in-php-by-gmail-server-or-own-domain-server/'>Asif18</a></b>"); //Put your body of the message you can place html code here
if ($_SESSION['enable_ssl'] = 1) { // 1 for true and 0 for false
$mail->SMTPSecure = '';
$mail->SmtpConnect();
}
$send = $mail->Send(); //Send the mails
if($send){
echo '<center><h3 style="color:#009933;">Mail sent successfully</h3></center>';
}
else{
echo '<center><h3 style="color:#FF3300;">Mail error: </h3></center>'.$mail->ErrorInfo;
}
?>
Instead of $_SESSION['enable_ssl'], you can use $_POST['enable_ssl'] as well if you're providing it right a way.
Hope this helps...

PHP mailer change sender address using yahoo.com

I am trying to change the sender address of the mail. Firstly I tried by gmail, then I let to know that by gmail its not possible now I am trying using Yahoo, and I got following error:-
SMTP ERROR: MAIL FROM command failed: 553 From address not verified.
Getting blank here I dont understand what do I do? Any help will be appreciated. following is my code:-
<?php
//date_default_timezone_set('Etc/UTC');
require('PHPMailerAutoload.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';
$body = 'This is the message';
$mail->IsSMTP();
$mail->Host = "plus.smtp.mail.yahoo.com";
//$mail->Host = 'smtp.gmail.com';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Username = 'myyahooid#yahoo.com';
$mail->Password = 'xyz';
$name='Test Name';
$mail->Sender='thishavetoset#domain.com';
//$mail->From = 'sender#senderdomain.com';
//$mail->FromName = 'Sender Name';
$mail->SetFrom('thishavetoset#domain.com', $name, TRUE);
$mail->AddReplyTo('no-reply#mycomp.com','no-reply');
$mail->Subject = 'subject';
$mail->MsgHTML($body);
$mail->AddAddress('myyahooid#yahoo.com', 'title1');
//$mail->AddAddress('abc2#yahoo.com', 'title2'); /* ... */
$fileName='../rough/test.pdf';
$mail->AddAttachment($fileName);
//$mail->send();
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
Let me know another solution to set the sender name also if you think, it can't be done this way. Thanks a ton in advance.
The sender email you using should be real email id and as your using Yahoo mail i think then it must registered in yahoo
There are two reasons smtp trows such error are.
first is You are attempting to send email to a domain that is not recognized by this server
second is You are attempting to relay email through this server and have not authenticated
Check if $mail->Sender='thishavetoset#domain.com'; email is set for your domain name your using.
So try to use email which user email password your using.
$mail->Username = 'myyahooid#yahoo.com';
In Gmail you can add that email id as external address from accounts and import tab >> add another email address, You will need details of smtp from the Admin of hosting/domain and add the email id.
once you add the external email address you can use that email id as sender from gmail smtp.

Could not send mail to other accounts apart from my own?

I've downloaded PHPMailer library from github and used the following script to send the mail. I've tried to send email to my own account and it worked. It printed "Message has been sent" and received the email in gmail. But when I tried sending mail to my friend's account, he didn't receive the email. But the script says message has been sent.
<?php
include('PHPMailer-master/PHPMailerAutoload.php');
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "example#gmail.com";
$mail->Password = "examplepassword";
$mail->SetFrom("example#gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("example2#gmail.com");
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I'm using xampp. What's the reason behind the problem, do I need to change any settings in my gmail settings?
EDIT: Now I got mail to second address but after 40 mins. But when I send it first address, it is received immediately. Don't know why? I want to use it for email address verification, 40 mins is very long.
below link will help you:
Sending emails through PHP mail is slow
http://stackoverflow.com/questions/6380477/sending-emails-through-php-mail-is-slow

PHPMailer setting for individual emails is sending empty To: fields

Using PHPMailer to send individual emails to recipients I'm getting nothing in the To: field when I add $mail->SingleTo = TRUE; to my code.
When I remove $mail->SingleTo = TRUE; I receive emails with an email address in the To: field that is correct.
This is what I get:
reply-to xxxxxx <xxxx#xxxx.com>, No Reply <no-reply#no-reply.com>
to
date Mon, Mar 21, 2011 at 5:07 PM
subject Testing
mailed-by gmail.com
signed-by gmail.com
(where xxxxxxx represents my email address.)
Here's my code:
if(isset($_POST['submit']))
{
require_once('PHPMailer_v5.1/class.phpmailer.php');
$mail = new PHPMailer();
$subject = $_POST['subject'];
$body = $_POST['emailbody'];
$to = $_POST['to'];
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "localhost"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "SSL"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "xxxxxxxxxx#gmail.com"; // GMAIL username
$mail->Password = "*********"; // GMAIL password
$mail->SetFrom('xxx#xxx.com', 'XXXXXX');
$mail->AddReplyTo("no-reply#xxxxx.com","No Reply");
$mail->Subject = $subject;
// After adding this line I'm getting an empty To: field
$mail->SingleTo = TRUE;
$mail->AddAddress("address1#xxxxxx.com", 'xyz abc');
$mail->AddAddress("address2#xxxxxx.com", 'abc xyz');
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
$message= "Mailer Error: " . $mail->ErrorInfo;
}
else
{
$message= "Message sent!";
}
}
You are using SMTP to send email. The phpmailer class is not using the SingleTo parameter when senting using Smtp.
More, if you see the CreateHeader function when the SingleTo == true the recipents are only aded to $this->SingleToArray and not to the header itself so basically it PHPmailer bug.
Looks like the only choice, unless you want to patch phpmailer, is to send email one-by-one without using SingleTo property
the solution will be
function & prepare_mailer($subject, $body) {
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "localhost"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "SSL"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "xxxxxxxxxx#gmail.com"; // GMAIL username
$mail->Password = "*********"; // GMAIL password
$mail->SetFrom('xxx#xxx.com', 'XXXXXX');
$mail->AddReplyTo("no-reply#xxxxx.com","No Reply");
$mail->Subject = $subject;
$mail->MsgHTML($body);
return $mail;
}
foreach( $_POST['to'] as $to ){
$mail = null;
$mail = & prepare_mailer($_POST['subject'],$_POST['body']);
$mail->AddAddress($to['address'], $to['name']);
$mail->Send();
}
Set up all the other parameters, then in a loop set the recipient, send the email, then use the ClearAllRecipients() function. Like so:
{ // loop start
$mail->AddAddress($person_email, $person_name);
$mail->Send();
$mail->ClearAllRecipients();
} // loop end
The problem is in the SmtpSend function (starting at line 701 in class.phpmailer.php). As you can see there, they don't take the singleTo setting into account, and just add all recipients and send the body of the message once.
So you should add some logic there to test if singleTo is true, and if it is modify the code so it sends these mails separately, prefixing the To: header to the body of the message. If singleTo is false you can call the code as-is (line 713 - 758).
Or alternatively, if you don't want to patch things, then you could use a transport method (ie. sendmail) that does seem to support the singleTo parameter.
$mail->AddAddress()
doesn't like CSV's
so if you have:
$Emails="addr1#host.com,addr2#host.net"; #etc;
do a for loop after a split:
$NewList = preg_split("/,/",$Emails);
foreach ($NewList as $k=>$email){
if ($k==0) $mail->AddAddress($email); # Add main to the "To" list.
else $mail->AddCC($email); # The REST to CC or BCC which ever you prefer.
}
-- BF.
SingleTo Is not a good idea. It only works with "sendmail" or "mail" transports, not with SMTP. If you use SingleTo with SMTP, this parameter is just ignored without any error or warning, and you may get duplicates.
Since you use both SingleTo an SMTP, as shown in your code, the SingleTo in your case is ignored.
The SMTP protocol is designed in a way that you cannot send one message to several different recipients, each having only its own address in the TO: field. To have each recipient have only its name in the TO:, the whole message have to be transmitted again. This explains why SingleTo is incompatible with SMTP.
According to the authors of the PHPMailer library, SingleTo is planned to be deprecated in the release of PHPMailer 6.0, and removed in 7.0. The authors have explained that it's better to control sending to multiple recipients at a higher level, since PHPMailer isn't a mailing list sender. They tell that the use of the PHP mail() function needs to be discouraged because it's extremely difficult to use safely; SMTP is faster, safer, and gives more control and feedback. And since SMTP is incompatible with SingleTo, the authors of PHPMailer will remove SingleTo, not SMTP.

Categories