Solved

VS 2008 C# eMail Sample

Posted on 2012-03-10
6
499 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:
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video discusses moving either the default database or any database to a new volume.

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now