Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

VS 2008 C# eMail Sample

Posted on 2012-03-10
6
Medium Priority
?
528 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
  • 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:
Meir Rivkin earned 2000 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

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:Meir Rivkin
Meir Rivkin earned 2000 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

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
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.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

885 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