I just need help. Basically I am creating a windows appllication that sends bulk emails to our customers. the field “email” and “attachment” are from database. the attachment field contains only the path where the file is located, The code is working but instead of receiving 5 emails , I receive 15 emails.
Note: my database contain only 5 records , therefore I should receive only 5 emails with attachments:
Can you help me please, Thanks!
Here is my code:
string email;
string attachment;
ArrayList emailList = new ArrayList();
ArrayList attachList = new ArrayList();
private static readonly Logger log = new _EventLogger();
private void btnSend_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmdgetEmail = new SqlCommand("Select EMAIL, PATH from MEMBERREQUIREMENTS WHERE STATUS=0", conn);
SqlDataReader getEmail = cmdgetEmail.ExecuteReader();
//count = 0;
while (getEmail.Read())
{
//count++;
//email = getEmail.GetValue(i).ToString();
//emailList.Add(email);
//i = i + 1 - 1;
email = getEmail.GetString(0);
emailList.Add(email);
attachment = getEmail.GetString(1);
attachList.Add(attachment);
}
getEmail.Close();
conn.Close();
sendMail();
}
private void sendMail()
{
string from="myemail@email.com";
foreach (string sendTo in emailList)
{
foreach (string sendAttachments in attachList)
{
MailMessage mail = new MailMessage();
mail.To.Add(sendTo);
mail.From = new MailAddress(from, "Company Name'", Encoding.UTF8);
mail.Subject = subject;
mail.Body = msgBodyHead + msgBodyHead2 + msgDate + msgGreet + msgBody + msgAdobe + msgAssistance + msgCompliment + msgfooter;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
mail.Attachments.Add(new Attachment(sendAttachments));
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(from, "password");
client.Host = "192.167.89.0";
client.EnableSsl = false;
try
{
progress();
client.Send(mail);
}
catch (Exception ex)
{
ProgressBar1.Visible = false;
timer1.Enabled = false;
Exception excpt = ex;
string errorMessage = string.Empty;
while (excpt != null)
{
errorMessage += excpt.ToString(); excpt = excpt.InnerException;
log.Error("Email - LMS Application Error", ex);
lblError.Text = "There was an error occured while processing your request.\n Please see Event Viewer for more details.";
lblError.ForeColor = System.Drawing.Color.Red;
}
}
}
}
}
It looks like you’re pulling a bunch of records from your
MEMBERREQUIREMENTStable containing an email address and a path to an attachment, and building a list of e-mail addresses and attachment paths.You’re then iterating over these sending, sending an e-mail for each combination of address and attachment. I’m guessing this is not what you want to do.
I imagine that either:
MEMBERREQUIREMENTStable.UPDATE:
Below is some code to do the former. Note that this is just a minimal edit of your posted code, and doesn’t fix variable names etc. or provide any additional error checking (which you probably want to do):