Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Sending C# emails using a SQL Query to get names for email address

Posted on 2013-01-29
8
Medium Priority
?
502 Views
Last Modified: 2013-01-30
I have an console application that gets the names along as other information from a stored proc then generates an email. My issue is that with some of the names come back as NULL in my stored proc when an email still needs to be send out becuse other names are returned. However, when the the C# code trys to insert a the name of the person in the stored proc where it is NULL the application closes becsue a blank value can not be placed in the TO: section of the email. Is there away to still send an email out when a Null value is returned for one name however there is a name for the other?
My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;

namespace EmailAEConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection("Data Source=ServerName;Initial Catalog=DataBaseName;User ID=ID;Password=Password");
            SqlCommand command = new SqlCommand("StoredProcName", conn);

            try
            {
                command.CommandType = CommandType.StoredProcedure;

                //Add data to DataTable
                DataTable dtbItems = new DataTable();
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(command))
                    sda.Fill(dtbItems);
                {
                    //GATHER OPP DATA
                    {
                        //Loop thru all the properties
                        foreach (DataRow row in dtbItems.Select())
                        {
                            string oppSalesPersonTeamAName = Convert.ToString(row["salespersonATeamName"]);
                            string oppSalesPersonATeamManagerName = Convert.ToString(row["salespersonAManagerName"]);
                            string oppIAMName = Convert.ToString(row["SalesPersonTeamBName"]);
                           ["estimatedclosedate"]);  <-----sometimes returns a null value

                            {
                                //****** NEED TO ADD "FOR EACH HERE ******
                                MailMessage mailAE = new MailMessage();

                                mailAE.From = new MailAddress("autogeneratedsystem@companyA.com");
                                mailAE.To.Add(oppSalesPersonTeamAName + "@companyA.com");
                                mailAE.To.Add(oppSalesPersonTeamBName + "@companyA.com");
                                mailAE.CC.Add(oppSalesPersonTeamAManagerName + "@companyA.com");
                                mailAE.Subject = " ****Warning****  Date Close (PO In) is estimated to close in the next 5 days: " + oppEstCloseDate.ToShortDateString() + "****Warning****";
                                mailAE.IsBodyHtml = true;
                                mailAE.BodyEncoding = System.Text.Encoding.UTF32;
                                mailAE.Body += "<br>Account Executive: " + oppSalesPersonTeamAName ;
                                mailAE.Body += "<br>IAM: " + oppSalesPersonTeamBName ;
                                mailAE.Body += "<br>Estimated Close Date: " + oppEstCloseDate.ToShortDateString();
                                mailAE.Body += "<br>";

                                SmtpClient s = new SmtpClient();
                                MailMessage m = new MailMessage();
                                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                                smtp.Host = "smtphostname";
                                smtp.Port = 25;
                                smtp.Send(mailAE);
                            }

                              conn.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR MESSAGE: " + ex.Message);
                conn.Close();
            }
        }
    }
}
0
Comment
Question by:newjeep19
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 38831504
if(row["SalesPersonTeamBName"] == null) continue;

 string oppIAMName = Convert.ToString(row["SalesPersonTeamBName"]);
                           ["estimatedclosedate"]);  <-----sometimes returns a null value

if(string.IsNullOrEmpty(oppIAMName)) continue;

Open in new window

0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 38831508
btw, next time put your code in a code brackets, it makes it easier to review the code.
0
 

Author Comment

by:newjeep19
ID: 38832966
Still not what I am looking for. When the value is null I still need to send out the email becsue the other names where found.

Results from stored proc"

First loop thru table
SalesPerson A = John Smith
Sales Person b = John Doe

Second loop thru table
SalesPerson A = Bill Jones
Sales Person b = " "

Email.....
First email from first loop:
TO: John Smith , John Doe

Second email sent from second loop
TO: Bill Jones

so even thought the second loop there was a null or blank value the email is still sent to Bill Jones
0
Industry Leaders: 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!

 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 38834198
static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection("Data Source=ServerName;Initial Catalog=DataBaseName;User ID=ID;Password=Password");
            SqlCommand command = new SqlCommand("StoredProcName", conn);

            try
            {
                command.CommandType = CommandType.StoredProcedure;

                //Add data to DataTable
                DataTable dtbItems = new DataTable();
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(command))
                {
                    sda.Fill(dtbItems);
                    {
                        //Loop thru all the properties
                        foreach (DataRow row in dtbItems.Select())
                        {
                            string salespersonATeamName = Convert.ToString(row["salespersonATeamName"]);
                            string SalesPersonTeamBName = Convert.ToString(row["SalesPersonTeamBName"]);
                            string salespersonAManagerName = Convert.ToString(row["salespersonAManagerName"]);

                            DateTime dtClosedDate = DateTime.MaxValue;
                            if (!DateTime.TryParse(row["estimatedclosedate"].ToString(), out dtClosedDate))
                            {
                                //failed get estimated closed date
                            }

                            MailMessage mailAE = new MailMessage();

                            mailAE.From = new MailAddress("autogeneratedsystem@companyA.com");

                            if (!string.IsNullOrEmpty(salespersonATeamName))
                            {
                                mailAE.To.Add(salespersonATeamName + "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(SalesPersonTeamBName))
                            {
                                mailAE.To.Add(SalesPersonTeamBName + "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(salespersonAManagerName))
                            {
                                mailAE.CC.Add(salespersonAManagerName + "@companyA.com");
                            }

                            mailAE.Subject = " ****Warning****  Date Close (PO In) is estimated to close in the next 5 days: " + oppEstCloseDate.ToShortDateString() + "****Warning****";
                            mailAE.IsBodyHtml = true;
                            mailAE.BodyEncoding = System.Text.Encoding.UTF32;
                            mailAE.Body += "<br>Account Executive: " + salespersonATeamName;
                            mailAE.Body += "<br>IAM: " + SalesPersonTeamBName;
                            if (dtClosedDate != DateTime.MaxValue)
                            {
                                mailAE.Body += "<br>Estimated Close Date: " + dtClosedDate.ToShortDateString();
                            }
                            mailAE.Body += "<br>";

                            SmtpClient s = new SmtpClient();
                            MailMessage m = new MailMessage();
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "smtphostname";
                            smtp.Port = 25;
                            smtp.Send(mailAE);
                        }
                    }
                }

                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR MESSAGE: " + ex.Message);
                conn.Close();
            }
        }

Open in new window

0
 

Author Comment

by:newjeep19
ID: 38835599
Thanks for sending this example however I still get an error message when trying to add a " " value to the TO fieled in the email when SalesPersonB is Null or blank. My updated code is below:
static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection("Data Source=ServerName;Initial Catalog=DataBaseName;User ID=ID;Password=Password");
            SqlCommand command = new SqlCommand("StoredProcName", conn);

            try
            {
                command.CommandType = CommandType.StoredProcedure;

                //Add data to DataTable
                DataTable dtbItems = new DataTable();
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(command))
                {
                    sda.Fill(dtbItems);
                    {
                        //Loop thru all the properties
                        foreach (DataRow row in dtbItems.Select())
                        {
                            string salespersonATeamName = Convert.ToString(row["salespersonATeamName"]);
                            string SalesPersonTeamBName = Convert.ToString(row["SalesPersonTeamBName"]);
                            string salespersonAManagerName = Convert.ToString(row["salespersonAManagerName"]);

                            DateTime dtClosedDate = DateTime.MaxValue;
                            if (!DateTime.TryParse(row["estimatedclosedate"].ToString(), out dtClosedDate))
                            {
                                //failed get estimated closed date
                            }
                         
                           if (string.IsNullOrEmpty(salespersonATeamName )) continue;
                            if (string.IsNullOrEmpty(salespersonBTeamName )) continue;
                            if (string.IsNullOrEmpty(salespersonAManagerName )) continue;


                            // No spaces allowed
                            string ASalesPersonshort_name = salespersonATeamName .Substring(0, 1).ToLower() + salespersonATeamName .Substring(salespersonATeamName .IndexOf(" ") + 1).ToLower();

                            string BSalesPersonshort_name = salespersonBTeamName .Substring(0, 1).ToLower() + salespersonBTeamName .Substring(salespersonBTeamName .IndexOf(" ") + 1).ToLower(); <---error  Message = "Index and length must refer to a location within the string.\r\nParameter name: length"

                            string salespersonAManagerName _name = salespersonAManagerName .Substring(0, 1).ToLower() + salespersonAManagerName .Substring(oppIAMName.IndexOf(" ") + 1).ToLower();


                            MailMessage mailAE = new MailMessage();

                            mailAE.From = new MailAddress("autogeneratedsystem@companyA.com");

                            if (!string.IsNullOrEmpty(ASalesPersonshort))
                            {
                                mailAE.To.Add(ASalesPersonshort+ "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(BSalesPersonshort))
                            {
                                mailAE.To.Add(BSalesPersonshort+ "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(salespersonAManagerName ))
                            {
                                mailAE.CC.Add(salespersonAManagerName + "@companyA.com");
                            }

                            mailAE.Subject = " ****Warning****  Date Close (PO In) is estimated to close in the next 5 days: " + oppEstCloseDate.ToShortDateString() + "****Warning****";
                            mailAE.IsBodyHtml = true;
                            mailAE.BodyEncoding = System.Text.Encoding.UTF32;
                            mailAE.Body += "<br>Account Executive: " + salespersonATeamName;
                            mailAE.Body += "<br>IAM: " + SalesPersonTeamBName;
                            if (dtClosedDate != DateTime.MaxValue)
                            {
                                mailAE.Body += "<br>Estimated Close Date: " + dtClosedDate.ToShortDateString();
                            }
                            mailAE.Body += "<br>";

                            SmtpClient s = new SmtpClient();
                            MailMessage m = new MailMessage();
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "smtphostname";
                            smtp.Port = 25;
                            smtp.Send(mailAE);
                        }
                    }
                }

                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR MESSAGE: " + ex.Message);
                conn.Close();
            }
        }

Open in new window


I added the short name to meet the context of the email thru our email system. I need the email to still send an email out even if salesPersonB is returned as null or blank in the stored proc. Before I added the short name code the app would still fail because I can't have a blank ( " " @companyA.com) in the To field in the email. Which in most cases the second sales person (salesPersonB) is blank .
Thanks
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 38835636
my bad, here:

static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection("Data Source=ServerName;Initial Catalog=DataBaseName;User ID=ID;Password=Password");
            SqlCommand command = new SqlCommand("StoredProcName", conn);

            try
            {
                command.CommandType = CommandType.StoredProcedure;

                //Add data to DataTable
                DataTable dtbItems = new DataTable();
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(command))
                {
                    sda.Fill(dtbItems);
                    {
                        //Loop thru all the properties
                        foreach (DataRow row in dtbItems.Select())
                        {
                            string salespersonATeamName = Convert.ToString(row["salespersonATeamName"]);
                            string SalesPersonTeamBName = Convert.ToString(row["SalesPersonTeamBName"]);
                            string salespersonAManagerName = Convert.ToString(row["salespersonAManagerName"]);

                            DateTime dtClosedDate = DateTime.MaxValue;
                            if (!DateTime.TryParse(row["estimatedclosedate"].ToString(), out dtClosedDate))
                            {
                                //failed get estimated closed date
                            }

 if (!string.IsNullOrEmpty(salespersonATeamName))
                            {
                            salespersonATeamName  = salespersonATeamName .Substring(0, 1).ToLower() + salespersonATeamName .Substring(salespersonATeamName .IndexOf(" ") + 1).ToLower();
}
 if (!string.IsNullOrEmpty(SalesPersonTeamBName ))
                            {
                            SalesPersonTeamBName = salespersonBTeamName .Substring(0, 1).ToLower() + salespersonBTeamName .Substring(salespersonBTeamName .IndexOf(" ") + 1).ToLower(); 
}

 if (!string.IsNullOrEmpty(salespersonAManagerName))
                            {
                            salespersonAManagerName  = salespersonAManagerName .Substring(0, 1).ToLower() + salespersonAManagerName .Substring(oppIAMName.IndexOf(" ") + 1).ToLower();
}

                            MailMessage mailAE = new MailMessage();

                            mailAE.From = new MailAddress("autogeneratedsystem@companyA.com");

                            if (!string.IsNullOrEmpty(SalesPersonTeamAName ))
                            {
                                mailAE.To.Add(SalesPersonTeamAName + "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(SalesPersonTeamBName ))
                            {
                                mailAE.To.Add(SalesPersonTeamBName + "@companyA.com");
                            }
                            if (!string.IsNullOrEmpty(salespersonAManagerName  ))
                            {
                                mailAE.CC.Add(salespersonAManagerName  + "@companyA.com");
                            }

                            mailAE.Subject = " ****Warning****  Date Close (PO In) is estimated to close in the next 5 days: " + oppEstCloseDate.ToShortDateString() + "****Warning****";
                            mailAE.IsBodyHtml = true;
                            mailAE.BodyEncoding = System.Text.Encoding.UTF32;
                            mailAE.Body += "<br>Account Executive: " + salespersonATeamName;
                            mailAE.Body += "<br>IAM: " + SalesPersonTeamBName;
                            if (dtClosedDate != DateTime.MaxValue)
                            {
                                mailAE.Body += "<br>Estimated Close Date: " + dtClosedDate.ToShortDateString();
                            }
                            mailAE.Body += "<br>";

                            SmtpClient s = new SmtpClient();
                            MailMessage m = new MailMessage();
                            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                            smtp.Host = "smtphostname";
                            smtp.Port = 25;
                            smtp.Send(mailAE);
                        }
                    }
                }

                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR MESSAGE: " + ex.Message);
                conn.Close();
            }
        }

Open in new window

0
 
LVL 42

Accepted Solution

by:
Meir Rivkin earned 2000 total points
ID: 38835640
you still need to verify that at least one name is valid, if not, display error message or something.
0
 

Author Comment

by:newjeep19
ID: 38835720
OK thanks that works great
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

618 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