ComponentPro UltimateMail

      Sending mail with attachments

      Language Filter: AllSend comments on this topic to ComponentPro

      MIME attachments are represented by Attachment objects, and are managed by use of the MailMessage.Attachments property. The source of attachments can be a file, a MemoryStream, or any other type of .NET Framework Stream. As a result, the ways an attachment can be created is limitless. This topic demonstrates two ways of creating an attachment.

      using System;
      using System.IO;
      using System.Windows.Forms;
      using ComponentPro.Net;
      using ComponentPro.Net.Mail;
      const string serverName = "myserver";
      const string user = "";
      const string password = "mytestpassword";
      const int port = 465;
      const SslSecurityMode securityMode = SslSecurityMode.Implicit;
      Smtp client = new Smtp();
          MailMessage mmMessage = new MailMessage();
          mmMessage.Subject = "Test Subject";
          mmMessage.BodyText = "Test Content";
          // Attach file to the message. 
          // Attach content data from a stream to the message. 
          Stream stream = new FileStream("myfile.dat", FileMode.Open);
          // The stream will be automatically closed after adding to the attachment list. 
          mmMessage.Attachments.Add(new Attachment(stream, "teststream"));
          Console.WriteLine("Connecting SMTP server: {0}:{1}...", serverName, port);
          // Connect to the server. 
          client.Connect(serverName, port, securityMode);
          // Login to the server. 
          Console.WriteLine("Logging in as {0}...", user);
          client.Authenticate(user, password);
          Console.WriteLine("Sending the message with attachment...");
          Console.WriteLine("Message sent...");
          // Disconnect. 
      catch (SmtpException smtpExc)
          MessageBox.Show(string.Format("An SMTP error occurred: {0}, ErrorStatus: {1}", smtpExc.Message, smtpExc.Status));
      catch (Exception exc)
          MessageBox.Show(string.Format("An error occurred: {0}", exc.Message));