Link to home
Start Free TrialLog in
Avatar of SirReadAlot
SirReadAlot

asked on

how to send emails with console app

Hi experts,

was just wondering how to do this------------------->

I have a console app with two methods, one method can query a database and shows [email address] while the other sends an email.

how can i combine both so that for each [email address] that is read in method one will be sent an email.


===========================
using System;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;

namespace EmailSender
{
    /// <summary>
    /// Email Sender is a console application designed to send e-mails to mace new starters.
    /// </summary>
    class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            RunStoredProc();
         }

   #region Database Connection Code
         // run a simple stored procedure
        public static void RunStoredProc()
        {
            SqlConnection conn = null;
            SqlDataReader rdr = null;
            try
            {
                // create and open a connection object
                conn = new
                SqlConnection("Database=xxxx;Data Source=xxxx;User ID=xxxxx;Password=xxxxx;");
                conn.Open();
                Console.WriteLine("Connection Successful");
                // create a command object identifying the stored procedure
                SqlCommand cmd = new SqlCommand("xxxxxxx", conn);
                //  set the command object so it knows to execute a stored procedure
                cmd.CommandType = CommandType.StoredProcedure;
                // execute the command
                rdr = cmd.ExecuteReader();
                // iterate through results, printing each to console
                while (rdr.Read())
                {
                    Console.WriteLine("t{0}\t{1}", rdr["ID"], rdr["Email"]);
                   // SendMail();
                }
            }
            finally
            {

                if (conn != null)
                {
                    conn.Close();
                }
                if (rdr != null)
                {
                    rdr.Close();
                }
                Console.Read();
            }
        }
   #endregion

   #region SendMail Code    
        public static void SendMail()
        {
            //Configure basic infomation for an e-mail message
            string FromName = "xxx";
            string FromEmail = "xxxxx@xxx.co.uk";
            string Subject = "Sample Email with attachment";
            string ToName = "xxxxx";
            string ToEmail = "xxxxx@xxxx.xx.xx";
               
            //Assign the attachment path
            string FileName = Environment.CurrentDirectory + @"\Attachments\NewStarter.doc";
         
            //Create the email server host
            System.Net.Mail.SmtpClient
            smtp = new System.Net.Mail.SmtpClient("mail.xxxx.co.uk");

            //Create the MailMessage object
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            //Assign from address
            msg.From = new System.Net.Mail.MailAddress(FromEmail, FromName);

            //Assign to address
            msg.To.Add(new System.Net.Mail.MailAddress(ToEmail, ToName));
         
            //assign subject, and body
            msg.Subject = Subject;
            msg.Body = "This is a test message with an attachment";
            msg.Priority = MailPriority.High;
         
            msg.Attachments.Add(new System.Net.Mail.Attachment(FileName));
            //Send the message with SmtpClient
                smtp.Send(msg);
        }
    }
   #endregion
}




Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Why is SendMail comment out here?

               while (rdr.Read())
                {
                    Console.WriteLine("t{0}\t{1}", rdr["ID"], rdr["Email"]);
                   // SendMail();

Bob
You are probably need to add arguments to SendMail allow for passing in arguments to change the properties for the MailMessage.

Bob
Avatar of SirReadAlot
SirReadAlot

ASKER

its commented out because i was testing else it will keep on sending me emails
how?
I don't know what information you have, but I could see where you need to pass in ToName and ToEmail:

   public static void SendMail(string ToName, string ToEmail)

and remove these 2 lines:

           string ToName = "xxxxx";
           string ToEmail = "xxxxx@xxxx.xx.xx";

Bob
 
will try this

those values are my name and email address
'my name' and 'email address' should be for FromName and FromEmail, would ya think?

Bob
yes it should be,

but i and sending all to myself. i am the sender and recipient.

ok--- i have swapped those to values, but how do i pass the email address to retrieved to the sending code?
I don't get what you are having problems understanding.

Bob
well, ur suggestion did not work thats why i asked again
Ok, what went wrong?

Bob
if i do this

public static void SendMail(string ToName, string ToEmail)

i get this error
Use of unassigned local variable


=============fullcode

using System;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;

namespace EmailSender
{
    /// <summary>
    /// Email Sender is a console application designed to send e-mails to mace new starters.
    /// </summary>
    class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            RunStoredProc();
         }

   #region Database Connection Code
         // run a simple stored procedure
        public static void RunStoredProc()
        {
            SqlConnection conn = null;
            SqlDataReader rdr = null;
           string ToName;==============tried to fix here
            string ToEmail;==============  tried to fix here

            try
            {
                // create and open a connection object
                conn = new
                SqlConnection("Database=xxxx;Data Source=xxxx;User ID=xxxxx;Password=xxxxx;");
                conn.Open();
                Console.WriteLine("Connection Successful");
                // create a command object identifying the stored procedure
                SqlCommand cmd = new SqlCommand("xxxxxxx", conn);
                //  set the command object so it knows to execute a stored procedure
                cmd.CommandType = CommandType.StoredProcedure;
                // execute the command
                rdr = cmd.ExecuteReader();
                // iterate through results, printing each to console
                while (rdr.Read())
                {
                    Console.WriteLine("t{0}\t{1}", rdr["ID"], rdr["Email"]);
                   // SendMail();
                    SendMail(ToName,ToEmail);==============errors here saying  Use of unassigned local variable 'ToName' etc

                }
            }
            finally
            {

                if (conn != null)
                {
                    conn.Close();
                }
                if (rdr != null)
                {
                    rdr.Close();
                }
                Console.Read();
            }
        }
   #endregion

   #region SendMail Code    
         public static void SendMail(string ToName, string ToEmail)============here
        {
            //Configure basic infomation for an e-mail message
            string FromName = "xxx";
            string FromEmail = "xxxxx@xxx.co.uk";
            string Subject = "Sample Email with attachment";
            string ToName = "xxxxx";
            string ToEmail = "xxxxx@xxxx.xx.xx";
               
            //Assign the attachment path
            string FileName = Environment.CurrentDirectory + @"\Attachments\NewStarter.doc";
         
            //Create the email server host
            System.Net.Mail.SmtpClient
            smtp = new System.Net.Mail.SmtpClient("mail.xxxx.co.uk");

            //Create the MailMessage object
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            //Assign from address
            msg.From = new System.Net.Mail.MailAddress(FromEmail, FromName);

            //Assign to address
            msg.To.Add(new System.Net.Mail.MailAddress(ToEmail, ToName));
         
            //assign subject, and body
            msg.Subject = Subject;
            msg.Body = "This is a test message with an attachment";
            msg.Priority = MailPriority.High;
         
            msg.Attachments.Add(new System.Net.Mail.Attachment(FileName));
            //Send the message with SmtpClient
                smtp.Send(msg);
        }
    }
   #endregion
}
I still see these lines:

       string ToName = "xxxxx";
       string ToEmail = "xxxxx@xxxx.xx.xx";

Bob
i don't know how to capture the email

Console.WriteLine("t{0}\t{1}", rdr["ID"], rdr["Email"]);

and replace it with
 public static void SendMail(string ToName, string ToEmail)
and
msg.To.Add(new System.Net.Mail.MailAddress(ToEmail, ToName));
sorry,

has been removed already, just repasted old code

I still see these lines:

       string ToName = "xxxxx";
       string ToEmail = "xxxxx@xxxx.xx.xx";

Bob
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks