Solved

C# code example where an email is sent to multiple recipients where the email address of the recipients comes from a stored proc

Posted on 2014-11-12
5
36 Views
Last Modified: 2016-06-15
I have an applicaion where the  an email is sent out to multiple recipients of a course when somthing about that course  has changed. I have a stored proc that gets the email address based off of the course id. I then send the email out reflecting the changes made to the course in an html formatted email.  The issue that I am running into is trying to get the email to go out to the multiple recipients  instead of the  last attended's email address found from the stored proc.
My code is listed below:
//Send email of course cancellation
                        StoredProcConnect sprocRoster = new StoredProcConnect("sp_GetRosterByCourseID");
                        sprocRoster.AddParameters("COURSEID");
                        sprocRoster.AddValues(id);
                        DataSet ds = sprocRoster.Select();
                        if (ds == null)
                            Response.Redirect("ErrorMsg.aspx?error=Problem Getting Roster Info.  Tech team has been notified, please try again");

                                MailAddressCollection coll = new MailAddressCollection();                     
   if (ds.Tables[0].Rows.Count > 0)
                        {
                               string To = string.Empty;
                            foreach (DataRow row in ds.Tables[0].Rows)
                            {
                                msg.To.Add(row["email"].ToString() + "@COMPANY.com");
                                To = (row["email"].ToString() + "@COMPANY.com");
                            }

                            //toAddress = new Array(To);

                            coll.Add(To);

                            msg.From = new MailAddress("ClassChange@allstate.com");
                            msg.Subject = "An update to " + courseName + " has been made!";

                            // SendEmail();
                            if (chkCourseName.Checked == true)
                            {
                              var Body = this.PopulateBody(courseName,
                              courseName + "  Has been changed!",
                              "A new entry will be sent to your Outlook Calendar."
                              + "Please remove the old entry and accept the new entry." + name, "Sorry for any inconvenience that this change may have occured. " + "<br/>" + lblPresenter + "<br/>");
                              this.SendHtmlFormattedEmail(To, "An update to " + courseName + " has been made!", Body);
                            }
                         }

private string PopulateBody(string courseName, string title, string url, string description)
        {
            string body = string.Empty;
            using (StreamReader reader = new StreamReader(Server.MapPath("~/HtmlPage1.html")))
            {
                body = reader.ReadToEnd();
            }
            body = body.Replace("{UserName}", courseName);
            body = body.Replace("{Title}", title);
            body = body.Replace("{Url}", url);
            body = body.Replace("{Description}", description);
            return body;
        }

        private void SendHtmlFormattedEmail(string recepientEmail, string subject, string Body)
        {
            using (MailMessage mailMessage = new MailMessage())
            {
                mailMessage.From = new MailAddress("Responses@COMPANY.com");
                mailMessage.Subject = subject;
                mailMessage.Body = Body;
                mailMessage.IsBodyHtml = true;
                mailMessage.To.Add(new MailAddress(recepientEmail));
                Smtp info goes here
            }
        }

Open in new window

0
Comment
Question by:newjeep19
5 Comments
 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
Comment Utility
do you want to send 1 email with BCC or a bunch of individual emails?

get your collection from the stored procedure into an array
one email for each returned address
 for (int counter=0; counter < array.count; counter++)
{
email.address = array[counter]
// rest of email
// email send routine
}
BCC
 for (int counter=0; counter < array.count; counter++) { bcc.address = bccaddress + "," +array[counter] }
// rest of email
// email send routine
0
 
LVL 6

Expert Comment

by:Mandeep Singh
Comment Utility
0
 
LVL 5

Accepted Solution

by:
ashokpumca earned 500 total points
Comment Utility
Hi,
Try the code below

                            SqlDataAdapter adpSamp = new SqlDataAdapter("Your Stored Procduere", con);
                            adpSamp.SelectCommand.CommandType = CommandType.StoredProcedure;
                            DataSet dsSamp = new DataSet();
                            adpSamp.Fill(dsSamp);
                            if (dsSamp.Tables[0].Rows.Count > 0)
                            {
                                MailMessage mail = new MailMessage();

                                for (int j = 0; j < dsSamp.Tables[0].Rows.Count; j++)
                                {
                                   
                                    String email = (dsIssue.Tables[0].Rows[j]["emailid"]).ToString();

                                    mail.To.Add(email);
                                    mail.Subject = "Mail Subject";
                                    mail.From = new MailAddress("Email ID of sender");

                                    mail.IsBodyHtml = true;
                                    mail.Priority = MailPriority.High;
                                    mail.Body = Your HTML Mail Format

                                    SmtpClient smtp = new SmtpClient("YOUR SMTP CLIENT");
                                    try
                                    {
                                        smtp.Send(mail);
                                    }
                                    catch (Exception ex)
                                    {
                                        LblMesg.Text = ex.Message.ToString();
                                    }
                                }
                            }
0
 

Author Comment

by:newjeep19
Comment Utility
worked
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This video discusses moving either the default database or any database to a new volume.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now