VS 2008 C# eMail Sample

I am trying to finish a program by adding the emailing attachments when the program finishes. I have taken the code below from the Microsoft sample code site.

----- if (answer.StartsWith("c") && mailSent == false) ---- On this line I am getting a message about "Object not set to an instance of an object"

What am I missing here?

--  I have this in my code to  CALL THE eMAIL SAMPLE PROGRAM

private void btneMail_Click(object sender, EventArgs e)
        {
           Process p = new Process();
           p.StartInfo.FileName = "C:\\Projects\\SendeMails\\SendeMails\\bin\\Debug\\SendeMails.exe";
           p.StartInfo.Arguments = "smtp.nycap.rr.com";
           p.StartInfo.UseShellExecute = false;
           p.StartInfo.RedirectStandardOutput = false;
           p.Start();
                     
           p.WaitForExit();
        }

---eMAIL SAMPLE PRoGRAM
namespace Examples.SmptExamples.Async
{
     

    public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
       
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            String token = (string)e.UserState;

            if (e.Cancelled)
            {
                MessageBox.Show("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                MessageBox.Show(token + " : " + e.Error.ToString());
            }
            else
            {
                MessageBox.Show("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            bool mailSent = false;

            try
            {
                // Command line argument must the the SMTP host.
                SmtpClient client = new SmtpClient(args[0]);
                // Specify the e-mail sender.
                // Create a mailing address that includes a UTF8 character
                // in the display name.
                MailAddress from = new MailAddress("jane@contoso.com",
                   "Jane " + (char)0xD8 + " Clayton",
                System.Text.Encoding.UTF8);
                // Set destinations for the e-mail message.
                MailAddress to = new MailAddress("rwheeler@rbsolutions.com");
                // Specify the message content.
                MailMessage message = new MailMessage(from, to);
                message.Body = "This is a test e-mail message sent by an application. ";
                // Include some non-ASCII characters in body and subject.
                string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
                message.Body += Environment.NewLine + someArrows;
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = "test message 1" + someArrows;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                // Set the method that is called back when the send operation ends.
                client.SendCompleted += new
                SendCompletedEventHandler(SendCompletedCallback);
                // The userState can be any object that allows your callback
                // method to identify this send operation.
                // For this example, the userToken is a string constant.
                string userState = "test message1";
                client.SendAsync(message, userState);
                Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
                string answer = Console.ReadLine();
                // If the user canceled the send, and mail hasn't been sent yet,
                // then cancel the pending operation.
                if (answer.StartsWith("c") && mailSent == false)
                {
                    client.SendAsyncCancel();
                }
                // Clean up.
                message.Dispose();
                MessageBox.Show("Goodbye.");
            }
            catch (Exception ex)
            {
                string eMsg = "003E: ERROR: " + ex.Message;
                eMsg += "\n" + ex.StackTrace;
                MessageBox.Show(eMsg);
            }
        }
    }
}
LVL 1
rwheeler23Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rwheeler23Author Commented:
May I add here that when I run this, I first get the message about cancelling, it does send the emails, and I get the prompt about emails sent. It is when I click on the emails sent messagebox that is when I get the error message. It as if it tries to look again and the field mailsent is not defined. I have not this AsyncCompletedEventArgs arguments before. Does this have something to do with this?
0
Meir RivkinFull stack Software EngineerCommented:
on the following line:
if (answer.StartsWith("c") && mailSent == false)

add a string check:

if (!string.IsNullOrEmpty(answer) && answer.StartsWith("c") && mailSent == false)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rwheeler23Author Commented:
That did the trick. Thanks.

If I may ask a follow up question here?

Now  that I have this working, I need to add attachments to this email. I know I can individually add files but I would like to add them via a wildcard. They all exist in the same folder and all have a csv extension. Can you provide a clue as to how to do this?
0
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

rwheeler23Author Commented:
I also just noticed something which is occurring due to my lack of understanding of asynchronous programming.   The way this code is set right now things happen in this order:
1) The message about pressing c to cancel appears
2) The email is sent
3) The message about message sent appears

Once the OK is click on the message sent box I want the window to close. If I remove the code for the message about cancelling and checking for message sent no emails are sent.

How do I adjust this code so that the messages are sent, the confirm box appears and the then the program exits?
0
Meir RivkinFull stack Software EngineerCommented:
assume your files are located under c:\temp
the following code loops through all csv files in folder and add them to the attachments collection.

example:
            foreach (var file in Directory.GetFiles(@"C:\temp", "*.csv"))
            {
                message.Attachments.Add(new Attachment(file));
            }

Open in new window

0
rwheeler23Author Commented:
The two answers were spot on, thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual C++.NET

From novice to tech pro — start learning today.