Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

VS 2008 C# eMail Sample

Posted on 2012-03-10
6
Medium Priority
?
518 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 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
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 

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 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

Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
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.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

670 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