phpmailer column loop & skip NULLs - phpmailer

I am trying to loop through 5 columns in a row to send an email with PHPmailer. Each row can contain up to 5 email addresses but not all do. My loop method works but if a NULL exists where no email address is available, the email does not get sent. How can I get my script to ignore NULLs. Also, is there a better loop process for Columns?
include("conn.php");
require("class.phpmailer.php");
// require("class.smtp.php");
// require("class.pop3.php");
$conn = mssql_connect($server, $user, $pass) or die("ERROR: Connection to MYSERVER failed");
$select = mssql_select_db($database, $conn) or die("ERROR: Selecting database failed");
$sql1 = "SELECT Email1 as email1, Email2 as email2, Email3 as email3, Email4 as email4, Email5 as email5 FROM $table2 where IPaddress='000.000.000.000'";
$result1 = mssql_query($sql1);
while ($row1 = mssql_fetch_assoc($result1)) {
$EmailADD1 = $row1["email1"];
$EmailADD2 = $row1["email2"];
$EmailADD3 = $row1["email3"];
$EmailADD4 = $row1["email4"];
$EmailADD5 = $row1["email5"];
//error_reporting(E_ALL);
error_reporting(E_STRICT);
ini_set('log_errors', 'On');
ini_set('display_errors', 'On');
date_default_timezone_set('America/Toronto');
//include ("class.phpmailer.php");
//include("class.smtp.php");
$mail = new PHPMailer();
$mail->SetLanguage('en', 'C:\PHP\mail\language\\');
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "me#me.net"; // specify main and backup server
$mail->Port = 25; // set the SMTP port
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "me"; // SMTP username
$mail->Password = "xxxxx"; // SMTP password
$mail->From = "me#me.net";
$mail->FromName = "Mailer";
//$body = $mail->getFile('contents.html');
//$body = eregi_replace("[\]", '', $body);
$mail->AddReplyTo("me#me.com", "JT");
$mail->From = "me#me.net";
//$mail->AddAddress("me#me.com", "JohnTest");
$mail->FromName = "Me";
$mail->Subject = "PHPMailer Test";
$mail->Body = "Hi,This is the HTML BODY$IP"; //HTML Body
$mail->WordWrap = 50; // set word wrap
$mail->AddAddress($EmailADD1, "IPscoreBounceInfo1");
$mail->AddAddress($EmailADD2, "IPscoreBounceInfo2");
$mail->AddAddress($EmailADD3, "IPscoreBounceInfo3");
$mail->AddAddress($EmailADD4, "IPscoreBounceInfo4");
$mail->AddAddress($EmailADD5, "IPscoreBounceInfo5");
...

You can solve this by eliminating the NULLs in your MySQL query from the server. Try this MySQL query instead, which should eliminate the NULLs:
SELECT * FROM (
SELECT Email1 as email FROM $table2 where IPaddress='000.000.000.000'
UNION
SELECT Email2 as email FROM $table2 where IPaddress='000.000.000.000'
UNION
SELECT Email3 as email FROM $table2 where IPaddress='000.000.000.000'
UNION
SELECT Email4 as email FROM $table2 where IPaddress='000.000.000.000'
UNION
SELECT Email5 as email FROM $table2 where IPaddress='000.000.000.000'
) WHERE email IS NOT NULL

Related

Docusign API - Self Signing

We have a requirement where we need to make a couple of PDF forms available using a HTML link to users for signing, but the signer should be a self-signer. In other words, once the signer completes signing using Docusign, they should be able to download the signed documents. However, we as the sender if the HTML link don't want to receive these saved documents as they have Personally Identifiable Information. The signer will upload these documents separately into our application at a later point.
I searched, but couldn't find a way to generate a HTML link for a self-signer. I was able to create a prototype that works for a regular signer, but not for a self-signer.
Any help would be much appreciated. Here's my code right snippet now:
// specify the document we want signed
string SignTest1File = #"C:\Users\skosuri.AA\Desktop\of0306.pdf";
string SignTest2File = #"C:\Users\skosuri.AA\Desktop\epa-credit-release-authorization.pdf";
// Enter recipient (signer) name and email address
string recipientName = "Chris";
string recipientEmail = "xxx.xxx#epa.gov";
// instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
string basePath = "https://demo.docusign.net/restapi";
// instantiate a new api client
ApiClient apiClient = new ApiClient(basePath);
// set client in global config so we don't need to pass it to each API object
Configuration.Default.ApiClient = apiClient;
string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// user might be a member of multiple accounts
accountId = loginInfo.LoginAccounts[0].AccountId;
Console.WriteLine("LoginInformation: {0}", loginInfo.ToJson());
// Read a file from disk to use as a document
byte[] fileBytes = File.ReadAllBytes(SignTest1File);
byte[] fileBytes2 = File.ReadAllBytes(SignTest2File);
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.EmailSubject = "Please complete and sign these documents";
// Add a document to the envelope
Document doc = new Document();
doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
doc.Name = "of0306.pdf";
doc.DocumentId = "1";
doc.TransformPdfFields = "true";
envDef.Documents = new List<Document>();
envDef.Documents.Add(doc);
// Add a second document to the envelope
Document doc2 = new Document();
doc2.DocumentBase64 = System.Convert.ToBase64String(fileBytes2);
doc2.Name = "epa-credit-release-authorization.pdf";
doc2.DocumentId = "2";
doc2.TransformPdfFields = "true";
envDef.Documents.Add(doc2);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Name = recipientName;
signer.Email = recipientEmail;
signer.RecipientId = "1";
signer.DefaultRecipient = "true";
// must set |clientUserId| to embed the recipient
signer.ClientUserId = "1234";
// Create a |SignHere| tab on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
signer.Tabs.DateSignedTabs = new List<DateSigned>();
signer.Tabs.FullNameTabs = new List<FullName>();
SignHere signHere = new SignHere();
signHere.AnchorString = "Applicant's Signature:";
signHere.AnchorXOffset = "1.5";
signHere.AnchorYOffset = "0";
signHere.AnchorIgnoreIfNotPresent = "false";
signHere.AnchorUnits = "inches";
signHere.DocumentId = "1";
signHere.RecipientId = "1";
signer.Tabs.SignHereTabs.Add(signHere);
DateSigned ds = new DateSigned();
ds.PageNumber = "3";
ds.XPosition = "380";
ds.YPosition = "550";
ds.DocumentId = "1";
ds.RecipientId = "1";
ds.TabLabel = "Date Signed";
signer.Tabs.DateSignedTabs.Add(ds);
// Create a |SignHere| tab on the second document for the recipient to sign
SignHere signHere2 = new SignHere();
signHere2.PageNumber = "1";
signHere2.XPosition = "80";
signHere2.YPosition = "375";
signHere2.DocumentId = "2";
signHere2.RecipientId = "1";
signer.Tabs.SignHereTabs.Add(signHere2);
FullName fn = new FullName();
fn.PageNumber = "1";
fn.XPosition = "80";
fn.YPosition = "300";
fn.DocumentId = "2";
fn.RecipientId = "1";
signer.Tabs.FullNameTabs.Add(fn);
DateSigned ds2 = new DateSigned();
ds2.PageNumber = "1";
ds2.XPosition = "80";
ds2.YPosition = "475";
ds2.DocumentId = "2";
ds2.RecipientId = "1";
signer.Tabs.DateSignedTabs.Add(ds2);
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
// set envelope status to "sent" to immediately send the signature request
envDef.Status = "sent";
// Use the EnvelopesApi to create and send the signature request
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = "https://www.epa.gov",
ClientUserId = "1234", // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = recipientName,
Email = recipientEmail
};
// create the recipient view (aka signing URL)
ViewUrl recipientView = envelopesApi.CreateRecipientView(accountId, envelopeSummary.EnvelopeId, viewOptions);
// print the JSON response
Console.WriteLine("ViewUrl:\n{0}", JsonConvert.SerializeObject(recipientView));
// Start the embedded signing session!
System.Diagnostics.Process.Start(recipientView.Url);
I don't quite understand your question.
Your app can use a "system user" (an email account such as "noreply#company.com") as the sender and present an embedded signing request to the "self-signer."
That way the "self-signer" can fill in the information and sign.
The signed document will only be visible (via DocuSign) to the system user. You can also set up a purge policy.
But it is not a friendly user experience to ask that the
signer will upload these documents separately into our application at a later point.
Instead, I suggest that you check out the concealValueOnDocument parameter of the text (data) tab.
Docs:
When set to true, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender.
When an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console.
This setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.
Using this setting enables the signer to see the PII when they sign, but the information is not visible to subsequent signers or viewers of the information.
The PII data is still available via the API so your integration can process it as necessary.

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!

activation of customer by sending link to his email using Suitelet Scripts

Overview:
I create one custom customer form using Suitelet Script with fields like name,email,phone in GET Method and the values entered in this fields obtained in the POST Method by request.getParameter() method. the customer record is created is successfully but when clicking the submit button the customer record is to be "inactive" mode and the url link is to sent to the customer email address ,when he clicks the link his record is to be changed to"active" mode this must be with in same suitelet page.
My Requirement:
I created the customer record successfully with INACTIVE MODE and link this send the customer mail but i need how to make the customer record to ACTIVE MODE when he clicks the link and the result is to be viewed in same suitelet page.
I have Given my code Sample Below:
function getCustomerInfo(request, response){
if(request.getMethod() == 'GET'){
//CREATING THE CUSTOM FORM AND ADDING FIELDS IN THE FORM
var form = nlapiCreateForm('Custom Customer Form');
form.addField('sfg_company', 'text', 'Company Name').setMandatory(true);
form.addField('sfg_address1','text','Address1');
form.addField('sfg_address2','text','Address2');
form.addField('sfg_city','text','City');
form.addField('sfg_state','text','State');
form.addField('sfg_emailaddr','email','Email').setMandatory(true);
form.addField('sfg_phone','phone','Phone');
form.addSubmitButton('Submit');
response.writePage(form);
}else{
nlapiLogExecution('DEBUG','form',form);
// CREATING THE RECORD BY GETTING THE VALUES ENTERED IN THE CUSTOM FORM
var compName = request.getParameter('sfg_company');
var compAdd1 = request.getParameter('sfg_address1');
var compAdd2 = request.getParameter('sfg_address2');
var cities = request.getParameter('sfg_city');
var stateName =request.getParameter('sfg_state');
var email_addr = request.getParameter('sfg_emailaddr');
var phone_num = request.getParameter('sfg_phone');
var newCust = nlapiCreateRecord('customer');
newCust.setFieldValue('companyname', compName);
newCust.setLineItemValue('addressbook', 'addr1', 1, compAdd1);
newCust.setLineItemValue('addressbook', 'addr2', 1, compAdd2);
newCust.setLineItemValue('addressbook', 'city', 1, cities);
newCust.setLineItemValue('addressbook', 'state', 1, stateName);
newCust.setFieldValue('email', email_addr);
newCust.setFieldValue('phone', phone_num);
newCust.setFieldValue('subsidiary', 1);
newCust.setFieldValue('isinactive','T');
//sending activation link to the customer
var sender = nlapiGetUser();
var receiver = email_addr;
var subject = 'Customer Activation Link';
var recordId = nlapiGetRecordId();
var url = "https://system.na1.netsuite.com/app/common/entity/custjob.nl?id="+recordId+"&whence=";
var body = 'Dear Customer,Your Record is Created Successfully and it will activated by click the following link :'+ url;
nlapiSendEmail(sender,receiver,subject,body);
var id = nlapiSubmitRecord(newCust);
nlapiSetRedirectURL('RECORD','customer',id,null,false);
}
}
It sounds like what you basically want is to send out a confirmation link to a customer that they can click and complete some sort of registration.
If you want to re-use your suitele code then you need to pass a custom stage or action parameter that you can trigger different actions from. e.g.:
var stage = request.getParameter('custparam_action') || 'showForm';
switch(stage){
case 'showForm': doShowForm(request, response); break;
case 'validate' : doValidate(request, response); break;
}...
Then the url you need to send out needs to reference the suitelet rather than the customer page in Netsuite:
var ctx = nlapiGetContext();
var url = nlapiResolveURL('SUITELET', ctx.getScriptId(), ctx.getDeploymentId(), true) +"&custparam_action=validate"+ getSecureValidationParams());
the function getSecureValidationParams should create some sort of time sensitive parameters including a hashed key. If the request passes validation then you would show whatever other form you want to show or redirect to or show a thank you page.
function getCustomerInfo(request, response){
if(request.getParameter('custscript_sfg_custmer_param') != null){
var value = request.getParameter('custscript_sfg_custmer_param')
var loadRecord = nlapiLoadRecord('customer',value);
loadRecord.setFieldValue('isinactive','F');
loadRecord.setFieldValue('custentity_sfg_referredby',1);
nlapiSubmitRecord(loadRecord);
nlapiSetRedirectURL('RECORD','customer',value);
}
if(request.getParameter('custscript_sfg_custmer_param') == null){
if(request.getMethod() == 'GET'){
//CREATING THE CUSTOM FORM AND ADDING FIELDS IN THE FORM
var form = nlapiCreateForm('Custom Customer Form');
form.addField('sfg_company', 'text', 'Company Name').setMandatory(true);
form.addField('sfg_address1','text','Address1');
form.addField('sfg_address2','text','Address2');
form.addField('sfg_city','text','City');
form.addField('sfg_state','text','State');
form.addField('sfg_emailaddr','email','Email').setMandatory(true);
form.addField('sfg_phone','phone','Phone');
form.addSubmitButton('Submit');
response.writePage(form);
}
}
if(request.getMethod() == 'POST'){
nlapiLogExecution('DEBUG','form',form);
// CREATING THE RECORD BY GETTING THE VALUES ENTERED IN THE CUSTOM FORM
var compName = request.getParameter('sfg_company');
var compAdd1 = request.getParameter('sfg_address1');
var compAdd2 = request.getParameter('sfg_address2');
var cities = request.getParameter('sfg_city');
var stateName =request.getParameter('sfg_state');
var email_addr = request.getParameter('sfg_emailaddr');
var phone_num = request.getParameter('sfg_phone');
var newCust = nlapiCreateRecord('customer');
newCust.setFieldValue('companyname', compName);
newCust.setLineItemValue('addressbook', 'addr1', 1, compAdd1);
newCust.setLineItemValue('addressbook', 'addr2', 1, compAdd2);
newCust.setLineItemValue('addressbook', 'city', 1, cities);
newCust.setLineItemValue('addressbook', 'state', 1, stateName);
newCust.setFieldValue('email', email_addr);
newCust.setFieldValue('phone', phone_num);
newCust.setFieldValue('subsidiary', 1);
newCust.setFieldValue('isinactive','T');
//sending activation link to the customer
var sender = nlapiGetUser();
var receiver = email_addr;
var subject = 'Customer Activation Link';
var recordId = nlapiGetRecordId();
var webAddress = "https://system.na1.netsuite.com"
var scriptType = nlapiGetContext().getScriptId();
var scriptId = nlapiGetContext().getDeploymentId();
var location = nlapiResolveURL('SUITELET',scriptType,scriptId);
var id = nlapiSubmitRecord(newCust);
var link = webAddress+location+'&custscript_sfg_custmer_param='+id+"&whence=";
var url = 'Click Here ';
var body = 'Dear Customer,Your Record is Created Successfully and it will activated by click the following link :'+ url;
nlapiSendEmail(sender,receiver,subject,body);
nlapiSetRedirectURL('SUITELET',scriptType,scriptId);
}
The above code will Get Customer Information through external Suitelet form and saving the record in the system.

Sending Emails in Sharepoint

I need to know what is the best practice for sending emails from my sharepoint webparts and/or customized features.
Should I just use the normal .Net classes to send email ? or is their a better way to do it through integration with an outlook server ?
Easy way is to use the built in Utilities, this will then use the mail server setttings setup in central admin
using Microsoft.SharePoint.Utilities;
SPUtility.SendEmail(SPContext.Current.Web, false, false,
"toaddress#mail.com", "subject",
"body");
Universal way to send email in any context(where SPWeb not available) is read OutboundMailService settings which is used in SPUtility. Then create SmtpClient manually:
var adminApp = SPAdministrationWebApplication.Local;
var instance = adminApp.OutboundMailServiceInstance;
var server = instance.Server.Address;
var defaultFrom = adminApp.OutboundMailSenderAddress;
var client = new SmtpClient();
client.Host = server;
message.From = new MailAddress(defaultFrom );
...
You also can use this code for dynamic mail id. this code gets the mail according to the user. I have used CAML query to get the data for the email content from the lists.
SPUser AssigUser = oWeb.EnsureUser(Assigned_Username);
SPQuery mquery = new SPQuery();
mquery.Query = #"<Where><Eq><FieldRef Name='Email_x0020_Type' />
<Value Type='Text'>Review - Ready for Review</Value>
</Eq></Where>";
string Emailsub = "";
string Emailbody = "";
SPList mList = oWeb.Lists["Email Content"];
SPListItemCollection itemcollection = mList.GetItems(mquery);
foreach (SPListItem item in itemcollection)
{
Emailsub = item["Email Subject"].ToString();
Emailbody = item["Email Content"].ToString();
SPUtility.SendEmail(oWeb, false, false, AssigUser.Email, Emailsub,
Emailbody + "</br>" + oWeb.Url);
break;
}
using overload with StringDictionary arguments (source)
StringDictionary headers = new StringDictionary();
headers.Add("to", currCtxt.Web.CurrentUser.Email);
headers.Add("cc", "xyz#abc.com");
headers.Add("bcc", "");
headers.Add("from", "email#add.com");
headers.Add("subject", "Email Subject");
headers.Add("content-type", "text/html");
string bodyText = "Hello how are you?";
SPUtility.SendEmail(currCtxt.Web, headers, bodyText.ToString());

Is there a PHPmailer parameter to limit re-sends?

When I use PHPmailer to send to a group of email addresses, it gets caught in a loop and keeps re-sending the email over and over (100 times or more). It doesn't always do this however. I can send to 10 or 12 addresses and it works fine. But a larger list (25 addresses) seems to have trouble. I did find some non-existent email addresses in my list that rebound back to my "from" address mailbox. So I thought that might be the problem. But, I ran a test with just 3 addresses (one non-existent) and it worked as expected (good addresses received the mail, and the bad one was rebounded back to the sender mailbox). No duplicate emails were sent.
I do use BCC to send my email, but I don't think that should matter. I'm wondering if maybe there is some parameter I can set for PHPmailer that will tell it not to re-send any emails. My web hosting site says it is not their server or mail system that is sending these emails, so I'm guessing it is something in PHPmailer.
When my real-life use of PHPmailer doesn't work like it did when I tested it, that makes it very difficult to fix. Anyone have any suggestions as to why my emails keep getting sent multiple times?
Also, I'd like to know if there's a way to stop PHPmailer, after $mail->Send() has been issued? I'm getting a little embarrassed with the spam-like behavior of my emails (and my users are getting mad).
My basic code is below. But, the PHP program code is the same in the cases where it works and doesn't work; it's just the input data that changes. When it has worked, there were 2 smaller arrays:
emailistAry(1) = array(email1,email2,email3,...email10) and
emailistAry(2) = array(email1,email2,email3,email4,email5).
When it keeps looping, there are 2 larger arrays:
emailistAry(1) = array(email1,email2,bademail1,email3,email4,bademail2,email5,...email25) and emailistAry(2) = array(mail26,email27,email28,bademail3,email29,...email50).
I haven't found the exact number that I can process successfully, because it would mean running tests that possibly fill people's mailboxes with endless multiple emails. No one wants that.
Here's my code:
<?php session_start();
// uses arrays of addresses to send emails to multiple people (with BCC)
require '../PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<link href="../root.css" rel="stylesheet" type="text/CSS"/>
<title> Website Notification </title>
<meta http-equiv= "content-type" content="text/html; charset=iso-8859-1"/>
</head>
<body>
<div style="top:0;padding:0;width:850px;margin-left:70px;">
<?php
//$emailistAry is gathered from addresses in a database.
// it contains 2 arrays of email arrays (multi-dimensional).
//$emailist_cnt is determined from building above array (currently a 2)
$fromaddr = "myaddress#mywebsite.org";
$toaddr = "groupaddress#mywebsite.com";
$rplyaddr = "my2address#gmail.com";
$subject = "--Special Notice--";
$messageH = "<p style='font-family:Arial,Helvetica,Georgia,\"Times New Roman\";font-size:90%;'>
<span style='font-size:120%;color:#336699;'>Greetings HLCA Member!</span> <br/><br/>".
"This is my message text....".
"</p>";
// Set mail environment variables
$mail->isSMTP();
$mail->Host = 'smtp.mywebsite.org';
$mail->SMTPAuth = true;
$mail->Username = $fromaddr;
$mail->Password = "mypasswd";
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Set mail details that remain constant for every recipient
$mail->SetFrom($fromaddr); // mailbox you want email to come from
$mail->AddAddress($toaddr); // set recipient group (empty mailbox)
$mail->AddReplyTo($rplyaddr); // where reject msgs are sent
$mail->Subject = make_goodemail($nly,'subj',$subject);
$mail->Body = $messageH;
$goodlist_cnt = $emailist_cnt;
$max_emails = 25; // max num emails per list
$bcc_out_total = 0; //number emails output with BCC
$badlist_cnt = 0;
$badlist = ''; // save emails that didn't get sent
$email_badlist = array(); // store email lists that didn't get sent
$duplist = "";
$stop_err = false;
$rcN = 0;
// Loop through email arrays and send one at a time (each contains an array of emails).
// (Note that we do not use the 0 array positions. First entries are in position 1.)
for ($i=1; $i <= $emailist_cnt; $i+=1) {
echo "<p style='margin-top:40px;font-size:120%;'><b> Processing list # ".$i."...</b></p>";
$duplist = "";
for ($j=1; $j <= $max_emails; $j+=1) {
// add addresses from this list array to BCC parameter,
if ($emailistAry[$i][$j] != '') {
// add current email to BCC for this list (save rc)
$BCCresult = $mail->AddBCC($emailistAry[$i][$j]);
if(!$BCCresult) {
$duplist = $duplist.$emailistAry[$i][$j].", ";
}
}
else {
$j = $max_emails; //set as end of list
}
} // for j loop
// Loop thru this BCC array and show list on screen.
$bccArray = $mail->GetBCCAddresses();
$bcc_out = 0;
echo "<br/>Mail BCC list: ";
for ($k=0;$k<=$max_emails;$k+=1) {
if ($bccArray[$k][0] != '') {
if ($k==0) { //first one
echo " ".$bccArray[$k][0]; } //no comma
else {
echo ", ".$bccArray[$k][0]; }
$bcc_out += 1;
}
else {
$k=$max_emails;
}
}
// $bcc_out_total = $bcc_out_total + $bcc_out;
echo "<br/>BCC count = ".$bcc_out;
if ($duplist != "") { //print duplicate list
echo "<br/> >>Duplicate or invalid emails not included: ".$duplist;
}
//echo "<br/><br/>would send email list here. webpass=".$webpass;
// ********** *********** ************* ************
// SEND THE MAIL with current BCC list of recipients.
// Output message indicating if mail for this group was successfully or not.
if (!$mail->Send()) { // Send mail, else save emailist.
// see if connection error, and process accordingly
$mail_err = $mail->ErrorInfo;
$pos = strpos($mail_err,'SMTP connect() failed');
if ($pos===true || $pos >= 0) {
$addmsg = "(Probably a password error. Try again.) <br/>";
if ($i == 1) { // connect error on first try, so
$stop_err = true; // stop processing cuz this error will continue
$rcN = 2;
}
}
else {
$addmsg = "";
$rcN = 1; //set general error for return
}
echo "<h4 style='color:red;margin-top:20px;margin-bottom:5px;text-align:center;'>
Problem sending emails. ".$addmsg." Mailer Error: ".$mail->ErrorInfo."</h4>";
echo "<h4 style='color:blue;margin-top:10px;margin-left:20px;margin-bottom:0px;'>Email List #".$i." not sent. </h4>";
if (!$stop_err) { //other error, so handle and keep going.
$goodlist_cnt = $goodlist_cnt - 1;
//save list in array (as one long string).
$badlist_cnt+=1;
$email_badlist[$badlist_cnt] = implode(",",$emailistAry[$i]); //save as a string
}
} //if !Mail-send
else { // Successful email
$bcc_out_total = $bcc_out_total + $bcc_out;
echo "<h4 style='color:blue;margin-top:20px;font-weight:bold;'>
Email group ".$i." sent successfully! </h4>";
}
// Clear cumulative recipient list for next loop
$mail->clearBCCs();
if ($stop_err) {
$i = $emailist_cnt; //set to last list so loop will stop
}
} // for i loop
if ($badlist_cnt > 0) { // error, but not stop_err, so lists are saved elsewhere.
$badlist_txt = "<span style='color:red;font-size:80%;'> (".$badlist_cnt." list(s) not sent)</span>";
//write badlists out to file for fixing and later processing
include ('includes/memNotifyErrSave.php');
}
else {
$badlist_txt = '';
}
if ($stop_err) {
echo "<br/> <h4 style='color:red;margin-top:50px;text-align:center;'> Processing stopped due to serious error! ".
"If password error, try again with correct password.<br/><br/>".
"<span style='font-size:120%;color:blue;font-weight:bold;'>* No emails were sent * </span></h4>";
}
else {
echo "<h4 style='color:blue;font-size:125%;font-weight:bold;margin-top:40px;'>
Sent this notice to ".$bcc_out_total." unique address(es), using ".$goodlist_cnt." email(s)".$badlist_txt.".</h4>";
}
// code for exit/return buttons
// Clear remaining cumulative lists
$mail->clearReplyTos();
$mail->clearAddresses();
?>
</div>
</body>
</html>

Resources