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
46 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 80

Expert Comment

by:David Johnson, CD, MVP
ID: 40438610
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
ID: 40439149
0
 
LVL 5

Accepted Solution

by:
ashokpumca earned 500 total points
ID: 40463822
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
ID: 40547441
worked
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

790 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