Solved

VS 2008 C# eMail Sample

Posted on 2012-03-10
6
512 Views
Last Modified: 2012-03-11
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);
            }
        }
    }
}
0
Comment
Question by:rwheeler23
[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
  • 4
  • 2
6 Comments
 

Author Comment

by:rwheeler23
ID: 37706012
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
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 37706741
on the following line:
if (answer.StartsWith("c") && mailSent == false)

add a string check:

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

Author Comment

by:rwheeler23
ID: 37706955
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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 

Author Comment

by:rwheeler23
ID: 37707021
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
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 500 total points
ID: 37707024
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
 

Author Closing Comment

by:rwheeler23
ID: 37707487
The two answers were spot on, thanks!
0

Featured Post

Independent Software Vendors: 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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

734 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