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
48 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

735 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